我有一个如下所示的XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<Items>
<Category Name="Alfa">
<Item Name="A1" Signature="3136323700000000"/>
<Item Name="A2" Signature="3136333400000000"/>
<Item Name="A3" Signature="3136323800000000"/>
<Item Name="A4" Signature="3136333300000000"/>
... More Items
</Category>
<Category Name="Beta">
<Item Name="B1" Signature="3136323700000000"/>
<Item Name="B2" Signature="3136333400000000"/>
<Item Name="B3" Signature="3136323800000000"/>
<Item Name="B4" Signature="3136333300000000"/>
... More Items
</Category>
... More Categories
</Items>
我想用它反序列化的类看起来像这样:
public sealed class Item
{
private String m_Category;
private String m_Name;
private String m_Signature;
public String Category
{
get { return m_Category; }
}
public String Name
{
get { return m_Name; }
}
public String Signature
{
get { return m_Signature; }
}
public Item(String category, String name, String signature)
{
m_Category = category;
m_Name = name;
m_Signature = signature;
}
}
如何反序列化它以便从父元素的Name属性中获取Category属性?如果不可能,我可以使用哪种替代方法?
答案 0 :(得分:1)
如何使用Linq To Xml?
var items = XDocument.Parse(xml)
.Descendants("Item")
.Select(c => new Item(c.Parent.Attribute("Name").Value,
c.Attribute("Name").Value,
c.Attribute("Signature").Value))
.ToList();