0

我有一个如下所示的 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 属性?如果不可能,我可以使用哪种替代方法?

4

1 回答 1

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();
于 2013-05-03T12:42:12.390 回答