Question

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>
Was it helpful?

Solution

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

OTHER TIPS

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; }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top