27

我有以下 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>

如何在类上定义 XML 序列化属性以支持所描述的场景?

4

1 回答 1

60

您需要使用XmlElement属性的命名空间来指示每个字段需要哪些命名空间。这将允许您将字段与特定命名空间相关联,但您还需要在类上公开一个返回类型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");
    }
}
于 2009-08-11T13:30:53.847 回答