I need to get plain xml, without the <?xml version="1.0" encoding="utf-16"?>
at the beginning and xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
in first element from XmlSerializer
. How can I do it?
views:
143answers:
3
+6
A:
You can use XmlWriterSettings and set the property OmitXmlDeclaration to true as described in the msdn. Then use the XmlSerializer.Serialize(xmlWriter, objectToSerialize) as described here.
tobsen
2009-11-20 17:49:15
+3
A:
Use the XmlSerializer.Serialize
method overload where you can specify custom namespaces and pass there this.
var emptyNs = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
serializer.Serialize(xmlWriter, objectToSerialze, emptyNs);
passing null or empty array won't do the trick
kossib
2009-11-22 22:11:39
Please note that you need to combine this answer with @tobsen's answer to get what I was asking for - a really clean xml!
Grzenio
2009-11-23 11:00:42
A:
To put this all together - this works perfectly for me:
// To Clean XML
public string SerializeToString(T value)
{
var emptyNamepsaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
var serializer = new XmlSerializer(value.GetType());
var settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
using (var stream = new StringWriter())
using (var writer = XmlWriter.Create(stream, settings))
{
serializer.Serialize(writer, value, emptyNamepsaces);
return stream.ToString();
}
}
Simon Sanderson
2010-09-17 02:10:32