在 C# 中获取 XML 文件中节点的值
本文关键字:节点 文件 XML 获取 | 更新日期: 2023-09-27 18:36:39
我一直在尝试读取给定菜单项的卡路里,但它不起作用。这是我的 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");
,因为它不知道是哪个项目。那么我如何告诉它获取名为"汉堡"的物品的卡路里呢?
//item[name='Burger']/卡路里