1

我想知道是否有一种方法使用 C# 使我能够返回与给定 XPath 查询匹配的 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>

如下所示:

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}

总结一下,我想知道如何创建一个函数,比如interestingFunction

谢谢

4

1 回答 1

1

一种方法是使用System.Xml.XPath.Extensions.XPathEvaluate.

例如

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();

或者,如果您更喜欢 XmlDocument:

var doc = new XmlDocument();
doc.Load(xmlFilePath);
string[] matchingValues = doc.SelectNodes(xPathQuery).Cast<XmlAttribute>().Select(x => x.Value).ToArray();
于 2012-10-18T09:54:33.523 回答