C#XmlSerializer:在嵌套对象上创建xmlns属性
我要使用的API要求我在嵌套元素上设置C#XmlSerializer:在嵌套对象上创建xmlns属性,c#,xml,xml-serialization,C#,Xml,Xml Serialization,我要使用的API要求我在嵌套元素上设置xmlns-属性,如下所示: <root> <mainelement> </mainelement> <mainelement> <subelement xmlns="http://example.com/xml" otherAttr="value"> </subelement> </mainelement> </
xmlns
-属性,如下所示:
<root>
<mainelement>
</mainelement>
<mainelement>
<subelement xmlns="http://example.com/xml" otherAttr="value">
</subelement>
</mainelement>
</root>
public class subelement
{
[XmlAttribute]
public string otherAttr { get; set; }
[XmlAttribute]
public string xmlns { get; set; } = "http://example.com/xml";
}
但是,当我尝试用XmlSerializer序列化根对象时,xmlns
-属性总是丢失。否则它就可以正常工作了。当我重命名它创建的属性时,我想它与保留关键字xmlns
有关
此外,我无法使用标准方法将名称空间设置为Serialize
方法的第三个参数,因为我只希望该属性位于子元素
对象上
有没有一种方法可以在序列化后不手动编辑文件就完成此操作 您需要在
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; }
}
请参阅,以获得一个有效的演示。只需在
子元素中设置