I am encountering the following problem. Whenever I use the default XML serialization in my C# class, the namespaces xsi
and xsd
are automatically added by the .NET serialization engine. However when the serialization is defined through IXmlSerializable
, the namespaces are not added.
Example: this code:
class Program
{
static void Main(string[] args)
{
OutputSerialized(new Outer() { Inner = new Inner() });
OutputSerialized(new OuterCustom() { Inner = new Inner() });
}
static void OutputSerialized<T>(T t)
{
var sb = new StringBuilder();
using (var textwriter = new StringWriter(sb))
new XmlSerializer(typeof(T)).Serialize(textwriter, t);
Console.WriteLine(sb.ToString());
}
}
[Serializable] public class Inner { }
[Serializable] public class Outer { public Inner Inner { get; set; } }
public class OuterCustom : IXmlSerializable
{
public Inner Inner;
public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteStartElement("Inner");
new XmlSerializer(typeof(Inner)).Serialize(writer, Inner);
writer.WriteEndElement();
}
public System.Xml.Schema.XmlSchema GetSchema() { return null; }
public void ReadXml(System.Xml.XmlReader reader) { /**/ }
}
produces the following output:
<?xml version="1.0" encoding="utf-16"?>
<Outer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Inner />
</Outer>
<?xml version="1.0" encoding="utf-16"?>
<OuterCustom>
<Inner>
<Inner xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
</Inner>
</OuterCustom>
You can see that the OuterCustom
's serialized form is missing the xsd
and xsi
namespaces.
How can I make my OuterCustom
behave the same way as Outer
? Am I missing something in my code? Am I doing the custom serialization wrong?
There are a lot of questions here on SO about how to get rid of the additional namespaces, but it seems that no one asked about how to get them back.