C# XmlSerializer:在嵌套对象上创建 xmlns 属性
C# XmlSerializer: Create xmlns attribute on a nested object
我想使用的 API 需要我在嵌套元素上设置 xmlns
属性,如下所示:
<root>
<mainelement>
</mainelement>
<mainelement>
<subelement xmlns="http://example.com/xml" otherAttr="value">
</subelement>
</mainelement>
</root>
subelement
的class是这样定义的:
public class subelement
{
[XmlAttribute]
public string otherAttr { get; set; }
[XmlAttribute]
public string xmlns { get; set; } = "http://example.com/xml";
}
但是,当我尝试使用 XmlSerializer 序列化根对象时,xmlns
-属性总是丢失。否则它工作正常。当我重命名它创建的这个属性时,我猜它与 xmlns
作为保留关键字有关。
此外,我无法使用将名称空间设置为 Serialize
方法的第三个参数的标准方法,因为我只希望此属性位于 subelement
对象上。
有没有办法在序列化后无需手动编辑文件的情况下完成此操作?
您需要在 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; }
}
有关工作演示,请参阅 this fiddle。
我想使用的 API 需要我在嵌套元素上设置 xmlns
属性,如下所示:
<root>
<mainelement>
</mainelement>
<mainelement>
<subelement xmlns="http://example.com/xml" otherAttr="value">
</subelement>
</mainelement>
</root>
subelement
的class是这样定义的:
public class subelement
{
[XmlAttribute]
public string otherAttr { get; set; }
[XmlAttribute]
public string xmlns { get; set; } = "http://example.com/xml";
}
但是,当我尝试使用 XmlSerializer 序列化根对象时,xmlns
-属性总是丢失。否则它工作正常。当我重命名它创建的这个属性时,我猜它与 xmlns
作为保留关键字有关。
此外,我无法使用将名称空间设置为 Serialize
方法的第三个参数的标准方法,因为我只希望此属性位于 subelement
对象上。
有没有办法在序列化后无需手动编辑文件的情况下完成此操作?
您需要在 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; }
}
有关工作演示,请参阅 this fiddle。