XML Serialization Namespaces

后端 未结 1 1016
情书的邮戳
情书的邮戳 2020-12-21 01:43

I have an issue with the Namespaces that my code is producing. What I\'d Like is the XML below:




        
相关标签:
1条回答
  • 2020-12-21 01:57
    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; }
    }
    
    0 讨论(0)
提交回复
热议问题