1

A simple pesron class with nested children class. Alll the properties are attributed and igonred the private field.

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.450")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[XmlRoot("person")]
public  class Person
{
    [XmlIgnore]
    int _id;
    [XmlIgnore]
    string _firstName;
    [XmlIgnore]
    string _lastName;
    [XmlIgnore]
    Person[] _children;
    public Person(){}
    public Person(int id, string firstName, string lastName)
    {
        this._id = id;
        this._firstName = firstName;
        this._lastName = lastName;
    }
    [XmlAttribute]
    public int Id { get { return _id; } }
    [XmlAttribute]
    public string FirstName { get { return _firstName; } }
    [XmlAttribute]
    public string LastName { get { return _lastName; } }
    [XmlElement("children")]
    public Person[] Children
    {
        get { return _children; }
        set { _children = value; }
    }
}

When the above type is serialized only the xml structre is created and ignoring the attributes. The output is

  <?xml version="1.0" encoding="utf-16" ?> 
<person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <children>
    <children>
      <children /> 
      <children /> 
     </children>
     <children>
      <children /> 
     </children>
   </children>
   <children /> 
  </person>
Rishi
  • 33
  • 6

2 Answers2

1

You need to add setters to your serializable properties. They will be ignored otherwise.

Chris Wallis
  • 1,263
  • 8
  • 20
1

You need the setters and also an Array of person as children

    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.450")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [XmlRoot("person")]
    public class Person
    {
        public Person() { }
        public Person(int id, string firstName, string lastName)
        {
            Id = id;
            FirstName = firstName;
            LastName = lastName;
        }
        [XmlAttribute]
        public int Id { get; set; }

        [XmlAttribute]
        public string FirstName { get; set; }

        [XmlAttribute]
        public string LastName { get; set; }

        [XmlArray("children")]
        [XmlArrayItem("person")]
        public Person[] Children { get; set; }
    }
HatSoft
  • 11,077
  • 3
  • 28
  • 43