Andy
Andy

Reputation: 281

Get a the value of a node in an XML file in C#?

I have been trying to get read the calories of a given menu item and it is not working. Here is what my XML file looks like.

<?xml version="1.0" encoding="utf-8" ?>
<menu>
 <!-- Burger -->
 <item>
   <name>Burger</name>
   <price>$5.99</price>
   <calories>500</calories>
   <description>A burger made with 100% Angus beef and grilled to your liking. Served with fries</description>
   <count>25</count>
  </item>
 </menu>

And my function that is trying to read the calories looks like this

public string calorieCount(int choice)
    {
        string calCount="";
        string path = "XMLFile1.xml";
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(path);
        XmlElement root = xmlDoc.DocumentElement;
        switch (choice)
        {
        case '0':
            //read the calories of burger and fries and return
            var node = root.SelectSingleNode("//item/name/calories");
            calCount = node.Value;
            break;
        }
       return calCount;
     }

I believe the problem is in var node = root.SelectSingleNode("//item/name/calories"); because it doesn't know which item. So how do I tell it to get the calories of the item with name "Burger"?

Upvotes: 1

Views: 52

Answers (1)

JustAndrei
JustAndrei

Reputation: 859

//item[name='Burger']/calories

Upvotes: 2

Related Questions