反序列化xmlarray的xml属性

时间:2013-07-26 14:38:01

标签: c# xml

我知道你不能在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;
    }

1 个答案:

答案 0 :(得分:4)

您可以将XmlArray替换为XmlElement

请参阅:How to add an attribute to a collection marked with 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);
}