views:

125

answers:

1

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;

    ...
+2  A: 

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;

    ...
}
Darin Dimitrov