1

一个带有嵌套子类的简单 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>
4

2 回答 2

1

您需要将设置器添加到您的可序列化属性中。否则它们将被忽略。

于 2012-07-29T07:58:41.697 回答
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; }
    }
于 2012-07-29T08:16:09.280 回答