问题
I have looked everywhere and not a single response is valid or the question is just slightly off to the point of not getting me the answer I need. Given all the searches I have looked for there seems to be one MASSIVE flaw in .Net's implementation of xml serialization.
Default:
[XmlRoot("root", Namespace="http://myclass.org/")]
public class MyClass
{
}
void Main() {
XmlSerializer ser = new XmlSerializer(typeof(MyClass));
XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
xsn.Add("mc", "http://myclass.org/");
ser.Serialize(new StreamWriter(Console.Out), new MyClass(), xsn);
}
OUTPUT:
<?xml version="1.0"?>
<mc:root xmlns:mc="http://myclass.org/">
</mc:root>
IXmlSerializable:
[XmlRoot("root", Namespace="http://myclass.org/")]
public class MyClass : IXmlSerializable
{
public XmlSchema GetSchema() {return null;}
public void ReadXml(XmlReader reader) {}
public void WriteXml(XmlWriter writer) {}
}
void Main() {
XmlSerializer ser = new XmlSerializer(typeof(MyClass));
XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
xsn.Add("mc", "http://myclass.org/");
ser.Serialize(new StreamWriter(Console.Out), new MyClass(), xsn);
}
OUTPUT:
<?xml version="1.0"?>
<root xmlns="http://myclass.org/">
</root>
WHY!
How do we fix this?
This is essential to figure out because without custom processing I will be forced to double step it, and process the serialized xml into an XmlDocument to fix this glitch. and yes, this HAS to be a glitch. I can work around everything else EXCEPT the root element.
I am not the only one who needs to know how to do this.
Thanks Jaeden "Sifo Dyas" al'Raec Ruiner
来源:https://stackoverflow.com/questions/31734779/ixmlserializable-and-root-element-prefix