XML Serialization in C# without XML attribute nodes
I have an XML document format from a legacy system that I have to support in a future application. I want to be able to both serialize and deserialize the XML between XML and C# objects, however, using the objects generated by xsd.exe, the C# serialization includes the xmlns:xsi..., xsi:... etc XML attributes on the root element of the document that gets generated. Is there开发者_运维百科 anyway to disable this so that absolutely no XML attribute nodes get put out in the resulting XML ? The XML document should be elements only.
Duplicate? XmlSerializer: remove unnecessary xsi and xsd namespaces
Yes, use the XmlSerializerNamespaces class.
Example:
var s= new System.Xml.Serialization.XmlSerializer(typeof(TypeToSerialize));
var ns= new System.Xml.Serialization.XmlSerializerNamespaces();
ns.Add( "", "");
System.IO.StreamWriter writer= System.IO.File.CreateText(filePath);
s.Serialize(writer, objectToSerialize, ns);
writer.Close();
See also: XmlSerializer: remove unnecessary xsi and xsd namespaces
There is no way to force XML Serializer to ignore xsi attributes (unless you implement IXmlSerializable and force custom serialization or use XmlAttributeOverrides). However the only time xsi: attributes show up is when you have a nullable element. If you do need to use nullable elements you can of course post-process the XML to remove all xsi: occurences. However if you do this think about how you will deserialize the XML back into an object, if xsi:nil is missing on an element and the element is defined as a nullable integer you will run into an exception.
@Cheeso, please correct me if i am wrong.
I have the following code.
public class TestSer
{
public int? MyProperty { get; set; }
}
TestSer ser = new TestSer();
ser.MyProperty = null;
StringBuilder bldr = new StringBuilder();
var ns = new System.Xml.Serialization.XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer s = new XmlSerializer(typeof(TestSer));
using (StringWriter writer = new StringWriter(bldr))
{
s.Serialize(writer, ser, ns);
}
I get the following output.
<?xml version="1.0" encoding="utf-16"?>
<TestSer>
<MyProperty d2p1:nil="true" xmlns:d2p1="http://www.w3.org/2001/XMLSchema-instance" />
</TestSer>
This isn't exactly element only as the question asks for.
精彩评论