在Xml序列化期间访问子节点

时间:2010-02-12 20:11:33

标签: c# xml xml-serialization

如何在序列化期间访问Name元素的子元素?

<Person>
    <Name>
        <First>John</First>
        <Middle>Adam</Middle>
        <Last>Smith</Last>
        <Madian></Madian>
    </Name>
    <Gender>M</Gender>
</Person>
[XmlRootAttribute("Person", IsNullable= false)]
public class Person
{
    [XmlElement(ElementName = "Name/First")]
    public string firstName;
    [XmlElement(ElementName = "Name/Middle", IsNullable = true)]
    public string middleName;
    [XmlElement(ElementName = "Name/Last")]
    public string lastName;
    [XmlElement(ElementName = "Name/Madian", IsNullable = true)]
    public string madianName;

    [XmlElement(ElementName = "Gender", DataType = "string")]
    public string gender;

    ...

2 个答案:

答案 0 :(得分:3)

    [XmlArray("Person")]
    [XmlArrayItem("Name", typeof(Name))]
    public List<Name> Name{ get; set; }

答案 1 :(得分:2)

您需要创建一个中间类:

public class Name
{
    [XmlElement(ElementName = "First")]
    public string firstName;
    [XmlElement(ElementName = "Middle", IsNullable = true)]
    public string middleName;
    [XmlElement(ElementName = "Last")]
    public string lastName;
    [XmlElement(ElementName = "Madian", IsNullable = true)]
    public string madianName;
}

然后在Person

中使用此类
[XmlRootAttribute("Person", IsNullable= false)]
public class Person
{
    public Name Name;

    [XmlElement(ElementName = "Gender", DataType = "string")]
    public string gender;

    ...
}