2013-10-22 44 views
1

我一直在嘗試讀取給定菜單項的卡路里,它不工作。這是我的XML文件的樣子。獲取C#中XML文件中節點的值?

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

我的功能正試圖讀取卡路里看起來像這樣

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; 
    } 

我相信這個問題是在var node = root.SelectSingleNode("//item/name/calories");,因爲它不知道哪個項目。那麼,如何告訴它獲取名稱爲「Burger」的物品的卡路里?

+0

對這個問題的正確標籤的XPath – JustAndrei

+0

謝謝你,我改變了標籤。 – Andy

回答

2

//項目[名稱=「漢堡」] /卡路里

+0

我應該將xmldocument更改爲xmlpath嗎?我收到了一個非常奇怪的錯誤。 – Andy