2011-04-27 118 views
1

您好我有XML字符串就像你可以看到下面如何用Linq解析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<Item> allitems = new Enumerable<Item>(); 

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

如何是可以做到的与使用LINQ?

+0

没有'Enumerable '这样的类。改为使用'List '。 – jeroenh 2011-04-27 15:46:40

+1

[LINQ读取XML(C#)]的可能重复(http://stackoverflow.com/questions/670563/linq-to-read-xml-c) – jeroenh 2011-04-27 15:49:13

回答

1

你有LINQ to XML你可以用它来查询XML使用LINQ

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)); 
} 
+0

击败我吧+1 – Jodrell 2011-04-27 15:55:37

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 
}