使用linqToXml从xml文档中获取值

时间:2011-03-23 14:05:28

标签: c# linq linq-to-sql

我无法理解这一点。我试过环顾四周,但我的查询不会产生任何结果。

这是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>

我的方法(未完成)

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;

}

1 个答案:

答案 0 :(得分: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");