I know you can't add an attribute to an XmlArray which I think is really unhandy. I know I can make a separate class for Phone, however, Phone belongs in Access. I have about 30 more nodes under access. How can I deserialize attribute 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;
}
You can replace the XmlArray
with an XmlElement
.
See: 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; }
}
Code:
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.