[英]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: 我想要使用的API需要我在嵌套元素上设置xmlns
-attribute,如下所示:
<root>
<mainelement>
</mainelement>
<mainelement>
<subelement xmlns="http://example.com/xml" otherAttr="value">
</subelement>
</mainelement>
</root>
The class of subelement
is defined like this: subelement
的类定义如下:
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. 但是,当我尝试使用XmlSerializer序列化根对象时, xmlns
-attribute始终缺失。 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. 当我重命名它创建的这个属性时,我想它与xmlns
因为它是保留关键字。
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. 此外,我无法使用标准方法将名称空间设置为Serialize
方法的第三个参数,因为我只希望此属性位于subelement
对象上。
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
. 您需要在mainelement
的subelement
属性上指定正确的命名空间。
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. 看一下工作演示的小提琴 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.