Accessing Child nodes during Xml Serialization

懵懂的女人 提交于 2021-02-11 13:18:09

问题


How can I access the children of the Name element during Serialization?

<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;

    ...

回答1:


You need to create an intermediary class:

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;
}

and then use this class inside Person:

[XmlRootAttribute("Person", IsNullable= false)]
public class Person
{
    public Name Name;

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

    ...
}



回答2:


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


来源:https://stackoverflow.com/questions/2254792/accessing-child-nodes-during-xml-serialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!