反序列化xmlarray的xml属性
本文关键字:属性 xml xmlarray 反序列化 | 更新日期: 2023-09-27 18:25:08
我知道你不能向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;
}
您可以用XmlElement
替换XmlArray
。
请参阅:如何将属性添加到用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);
}