简体   繁体   中英

C# XmlSerializer: Create xmlns attribute on a nested object

The API I want to use requires me so set the xmlns -attribute on a nested element, like this:

<root>
   <mainelement>
   </mainelement>
   <mainelement>
      <subelement xmlns="http://example.com/xml" otherAttr="value">
      </subelement>
   </mainelement>    
</root>

The class of subelement is defined like this:

public class subelement
{
    [XmlAttribute]
    public string otherAttr { get; set; }
    [XmlAttribute]
    public string xmlns { get; set; } = "http://example.com/xml";
}

However, when I try to serialize the root object with XmlSerializer the xmlns -attribute is always missing. Otherwise it's working fine. When I rename this attribute it created, so I guess it has something to do with xmlns as reserved keyword.

Also I am not able to use the standard way of setting namespaces as third parameter of the Serialize method because I just want this attribute to be on the subelement object.

Is there a way to accomplish this without manually editing the file after serialization?

You need to specify the correct namespace on the subelement property in mainelement .

public class mainelement
{
    [XmlElement(Namespace = "http://example.com/xml")]
    public subelement subelement { get; set; }
}

public class subelement
{
    [XmlAttribute]
    public string otherAttr { get; set; }    
}

See this fiddle for a working demo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM