c# - 在 XML 中搜索元素

标签 c# xml search xml-parsing

我有一个类似的 XML 文件,我需要搜索它的值.. 就像输入产品名称时应该显示相关价格一样

是否有比解析和循环搜索值更简单的方法?

<products>
    <product>
      <Name> PRODUCT 1</Name>
      <price>150</price>
    </product>
    <product>
      <Name> PRODUCT 2</Name>
      <price>250</price>
    </product>
    <product>
      <Name> PRODUCT 3</Name>
      <price>300</price>
    </product>
  <products>

最佳答案

您可以使用 XPath:

XmlDocument doc = new XmlDocument();
doc.Load("myfile.xml");
XmlNode myPrice = doc.SelectSingleNode("/products/product[Name=' PRODUCT 1']/price");
Console.WriteLine(myPrice.InnerText);

输出

150

请注意,您的产品标识符之前的空格很重要。

如果愿意,您可以使用 XPathDocument 做同样的事情:

XPathDocument doc = new XPathDocument("myfile.xml");
XPathNavigator xpath = doc.CreateNavigator();
XPathNavigator myPrice = xpath.SelectSingleNode("/products/product[Name=' PRODUCT 1']/price");
Console.WriteLine(myPrice.ToString());

也输出

150

在 .NET 2.0 中测试了这两个。

关于c# - 在 XML 中搜索元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6483146/

相关文章:

android - 如何解决org.simpleframework.xml.core.ValueRequiredException : Unable to satisfy @org. simpleframework.xml.ElementList()

Android 百分比布局高度

android搜索多个关键字

search - 如何在网站的所有文件夹/文件中搜索代码片段?

c# - 在 Entity Framework Power tools beta 2 中首次使用逆向工程代码之后移动生成的类

C# 与 SQLite 和外键

c# - 位置 inheritInChildApplications 杀死调试器?

c# - 使用 C# 从 BitmapData 裁剪区域

php - 在子目录中搜索页面,并在友好 URL (htaccess) 中使用额外参数

c# - 使用递归函数解析xml值时出错