简体   繁体   English

如何从与C#中的XPath查询匹配的XML文件中获取值

[英]How to get values from an XML file matching XPath query in C#

I'm wondering whether there is a way using C# which enables me to return all the inner values within an XML file matching a given XPath query. 我想知道是否存在使用C#的方法,该方法使我能够返回与给定XPath查询匹配的XML文件中的所有内部值。

Let's suppose that we have the following Xml file named exampleWithFruits.xml: 假设我们有以下名为exampleWithFruits.xml的Xml文件:

<fruits>
   <bananas>
      <banana id="1" color="yellow" price="0.5" />
      <banana id="2" color="yellow" price="0.4" />
      <banana id="3" color="yellow" price="0.6" />
   </bananas>
   <apples>
      <apple id="1" color="red" price="0.5" />
      <apple id="2" color="red" price="0.4" />
      <apple id="3" color="green" price="0.6" />
      <apple id="4" color="yellow" price="0.4" />
   </apples>
   <oranges>
      <orange id="1" color="orange" price="0.5" />
      <orange id="2" color="orange" price="0.5" />
   </oranges>
</fruits>

Something like following below: 如下所示:

string xmlFilePath = "exampleWithFruits.xml";
string xPathQuery = "//fruits/apples//@color"
string[] matchingValues = interestingFunction(xmlFilePath, xPathQuery);
//for instance we would get something like : matchingValues = {red, red, green, yellow}

To sum up, I would like to know how to create a function such as interestingFunction 综上所述,我想知道如何创建一个有趣的函数

Thx 谢谢

One way to do this is to use System.Xml.XPath.Extensions.XPathEvaluate . 一种方法是使用System.Xml.XPath.Extensions.XPathEvaluate

Eg 例如

string xmlFilePath = "exampleWithFruits.xml";
string xPathQuery = "//fruits/apples//@color";

var doc = XDocument.Load(xmlFilePath);
IEnumerable att = (IEnumerable)doc.XPathEvaluate(xPathQuery);
string[] matchingValues = att.Cast<XAttribute>().Select(x => x.Value).ToArray();

Or if you prefer XmlDocument: 或者,如果您更喜欢XmlDocument:

var doc = new XmlDocument();
doc.Load(xmlFilePath);
string[] matchingValues = doc.SelectNodes(xPathQuery).Cast<XmlAttribute>().Select(x => x.Value).ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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