XML Serialization Namespaces

女生的网名这么多〃 提交于 2019-11-29 14:36:11
dbc
  1. You can add xsi:schemaLocation by adding a synthetic property along the lines of the answer in How to add xsi schemalocation to root c # object XmlSerializer -- but use a property instead of a field. If you use a field you will actually add to the footprint of your class in memory.

  2. To define a default namespace xmlns="http://www.nrf-arts.org/namespace", you can apply [XmlRoot("ClassToSerialize", Namespace="http://www.nrf-arts.org/namespace")] to your ClassToSerialize or allocate an XmlRootAttribute override and pass it to the XmlSerializer constructor. Be sure to cache the serializer if you do the latter.

  3. Other than implementing IXmlSerializable, which is somewhat burdensome, I don't know if it's possible to control the attribute order with XmlSerializer. However, the XML specification states "the order of attribute specifications in a start-tag or empty-element tag is not significant", so I recommend not worrying about it.

Thus the following should do the trick. Note I moved your GetNameSpace() inside ClassToSerialize and renamed it GetAdditionalNamespaces():

[XmlRoot("ClassToSerialize", Namespace="http://www.nrf-arts.org/namespace")]
public class ClassToSerialize
{
    public static XmlSerializerNamespaces GetAdditionalNamespaces()
    {
        XmlSerializerNamespaces xsNS = new XmlSerializerNamespaces();

        xsNS.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        xsNS.Add("Test", "http://www.Test.org/");

        return xsNS;
    }

    [XmlAttribute("schemaLocation", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public string XSDSchemaLocation
    {
        get
        {
            return "http://www.123.org/namespace C:\\Schema\\ClassToSerialize.xsd";
        }
        set
        {
            // Do nothing - fake property.
        }
    }

    [XmlAttribute()]
    public string Type { get; set; }

    [XmlAttribute()]
    public string Name { get; set; }

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