2011-03-23 114 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