1

我知道您不能向我认为非常不方便的 XmlArray 添加属性。我知道我可以为 Phone 创建一个单独的类,但是,Phone 属于 Access。我还有大约 30 个正在访问的节点。如何反序列化属性 hasTextField?

    <Access>
       <Phone hasTextField="true">
          <Item description="Skype" />
          <Item description="IP Phone" />
       </Phone>
       <Computer>
          <Item description="PC" />
          <Item description="Laptop" />
       </Computer>
    </Access>


   [XmlRoot("Access")]

    public class Access
    {
       public Access(){}

       [XmlArray("Phone")]
       [XmlArrayItem("Item")]
       public AccessItem[] ItemList;

       [XmlArray("Computer")]
       [XmlArrayItem("Item")]
       public AccessItem[] ItemList;
    }
4

1 回答 1

4

您可以将 替换XmlArrayXmlElement

请参阅:如何向标有 XmlArrayAttribute 的集合添加属性?

[XmlType("Access")]
public class Access
{
   [XmlElement("Phone")]
   public AccessItem Phone { get; set; }

   [XmlElement("Computer")]
   public AccessItem Computer { get; set; }
}

public class AccessItem
{
    public AccessItem()
    {
        Items = new List<Item>();
    }

    [XmlAttribute("hasTextField")]
    public bool HasTextField { get; set; }

    [XmlElement("Item")]
    public List<Item> Items { get; set; }
}

[XmlType("Item")]
public class Item
{
    [XmlAttribute("description")]
    public string Description { get; set; }
}

代码:

var data = @"<Access>
   <Phone hasTextField=""true"">
      <Item description=""Skype"" />
      <Item description=""IP Phone"" />
   </Phone>
   <Computer>
      <Item description=""PC"" />
      <Item description=""Laptop"" />
   </Computer>
</Access>";

var serializer = new XmlSerializer(typeof(Access));

Access access;

using(var stream = new StringReader(data))
using(var reader = XmlReader.Create(stream))
{
    access = (Access)serializer.Deserialize(reader);
}
于 2013-07-26T14:51:31.470 回答