带有嵌套子类的简单pesron类。所有属性都归属于私人领域。
[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; }
}
}
当序列化上述类型时,仅创建xml结构并忽略属性。 输出是
<?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>
答案 0 :(得分:1)
您需要将setter添加到可序列化属性中。否则他们将被忽略。
答案 1 :(得分:1)
您需要设置者以及作为孩子的人数组
[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; }
}