简体   繁体   中英

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"?

//项[名= '汉堡'] /卡路里

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM