问题
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