带有父属性的XML反序列化
本文关键字:XML 反序列化 属性 | 更新日期: 2023-09-27 18:11:54
我有一个看起来像这样的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;
}
}
我如何反序列化它,以便Category属性取自父元素的Name属性?如果不可能,我可以使用哪种替代方法?
如何使用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();