如何用Linq解析xml?

时间:2011-04-27 15:42:47

标签: c# linq-to-xml

您好我有xml字符串,如下所示

 <?xml version="1.0" encoding="ISO-8859-1" ?> 
- <Result>
    - <AllItems>
        - <Item attribute="123">
              <SubItem subAttribute="1" /> 
              <SubItem2 subAttribute2="2" /> 
          </Item>
        - <Item attribute="321">
              <SubItem subAttribute="3" /> 
              <SubItem2 subAttribute2="4" /> 
          </Item>
      </AllItems>
  </Result>

我想让allitems元素中的每个项获取属性值并将它们添加到Enumerable类

Enumerable<Item> allitems = new Enumerable<Item>();

public class Item()
{
     public string attribute{get;set;}
     public string subattribute{get;set;}
     public string subattribute2{get;set;}
}

如何使用LINQ完成?

3 个答案:

答案 0 :(得分:3)

你的例子在Linq to XML中看起来像这样:

XDocument doc = XDocument.Load("test.xml");
var allItems = doc.Descendants("Item").Select(x => new Item() 
{
    attribute = x.Attribute("attribute").Value,
    subattribute = x.Element("SubItem").Attribute("subAttribute").Value,
    subattribute2 = x.Element("SubItem2").Attribute("subAttribute2").Value
});

foreach (var item in allItems)
{
    Console.WriteLine(string.Format("{0}: {1} / {2} ", item.attribute, 
                                                       item.subattribute, 
                                                       item.subattribute2));
}

答案 1 :(得分:2)

这些内容将直接转化为您的课程:

var allItems = from item in XDocument.Load("myxmlfile.xml").Descendants("Item")
    select new Item()
    {
        attribute = (string)item.Attribute("attribute"),
        subattribute = (string)item.Element("SubItem1").Attribute("subAttribute"),
        subattribute2 = (string)item.Element("SubItem2").Attribute("subAttribute")
    };

foreach(Item item in allItems)
{
    // your logic here
}

答案 2 :(得分:1)

您可以使用LINQ to XML通过LINQ

查询XML