Pio*_*iak 26 .net xml xml-serialization xml-namespaces
我有以下XML:
<person xmlns:a="http://example.com" xmlns:b="http://sample.net">
<a:fName>John</a:fName>
<a:lName>Wayne</a:lName>
<b:age>37</b:age>
</person>
Run Code Online (Sandbox Code Playgroud)
如何在类上定义XML序列化属性以支持所描述的场景?
Zac*_*ham 56
您需要使用XmlElement属性的Namespace指示每个字段所需的命名空间.这将允许您将字段与特定命名空间相关联,但您还需要在类上公开返回类型XmlNamespaceDeclarations的属性以获取前缀关联.
请参阅下面的文档和示例:
[XmlRoot(ElementName = "person")]
public class Person
{
[XmlElement(Namespace = "http://example.com")]
public string fname;
[XmlElement(Namespace = "http://sample.com")]
public string lname;
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();
public Person()
{
xmlns.Add("a", "http://example.com");
xmlns.Add("b", "http://sample.com");
}
}
Run Code Online (Sandbox Code Playgroud)