How to add xsi schemalocation to root c # object XmlSerializer

后端 未结 2 1369
情歌与酒
情歌与酒 2020-12-09 18:34

I am using XmlSerializer to create an object representing an XML file and now i want to add a schemalocation to the rootelement of my xml file. I can add namespaces like the

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 18:55

    The XSD.exe generates partial classes, so you can add your own separate partial class to hold things like xsi:schemaLocation as fields or properties.

    So, adding to @Petru Gardea's sample elementB class, you only need to create another file in your project and add this partial class:

    public partial class elementB 
    {
        [XmlAttributeAttribute("schemaLocation", Namespace="http://www.w3.org/2001/XMLSchema-instance")]
        public string xsiSchemaLocation = "http://www.acme.com/xml/OrderXML-1-0.xsd";
    }
    

    There is one gotcha that I ran into doing this and that was by default xsd.exe does not add a namespace to the generated file(s). When you create this partial class of your own, it will most likely be in a namespace. Since <default namespace> and an explicitly defined namespace do not match, partial won't work. So, you need to use the namespace option on xsd.exe to actually get the generated classes into your namespace.

提交回复
热议问题