2011-03-23 84 views
0

我只是无法弄清楚这个问题。我试过四处寻找,但我的查询不会产生任何结果。从linqToXml的xml文档中获取值

这是XML:

<?xml version="1.0" encoding="utf-8" ?> 
<Prices> 
    <PricePerItem> 
    <Item Name="Milk, Low fat, 1Liter">11.2</Item> 
    <Item Name="Butter">17</Item> 
    <Item Name="Bread">12.2</Item> 
    <Item Name="Cheese">15.5</Item> 
    </PricePerItem> 
    <PricePerKg> 
    <Item Name="Apple, Jonagold">13.4</Item> 
    <Item Name="Chicken">12.5</Item> 
    <Item Name="Salad">9.6</Item> 
    <Item Name="Fish, Salmon">14</Item> 
    </PricePerKg> 
</Prices> 

而且我的方法(没有做OFC)

private static Dictionary<string, int> GetPrizesFromXML() 
{ 
    //Read the values from the XMLDoc 
    XElement xml = XElement.Load("prices.xml"); 
    var prizes = from q in xml.Elements("Prices") 
       select q.Elements("Item"); 
    foreach (var prize in prizes) 
    { 
     Console.Out.WriteLine(prize.ToString()); 
    } 

    return null; 

} 

回答

3

改变这一行:

var prizes = from q in xml.Elements("Prices") 
      select q.Elements("Item"); 

这样:

var prizes = from q in xml.Elements("Prices") 
      select q.Descendants("Item"); 
+0

对不起,因为旧的浏览器无法赞成。尽管现在做了。谢谢! – Phil 2011-03-25 13:47:40

+0

@Phil如果它对你有用,请点击复选标记将其标记为答案。 – 2011-03-25 15:01:59