Phil
Phil

Reputation: 3994

Get values from xml document with linqToXml

I just can't get this figured out right. I've tried looking around but my queries won't render any results.

This is the 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>

And my method (not done 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;

}

Upvotes: 0

Views: 91

Answers (1)

Brian Driscoll
Brian Driscoll

Reputation: 19635

Change this line:

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

to this:

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

Upvotes: 3

Related Questions