IXmlSerializable and Root Element Prefix

為{幸葍}努か 提交于 2020-01-06 18:32:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!