如何在C#中匹配XPath查询的XML文件中获取值 [英] How to get values from an XML file matching XPath query in C#
本文介绍了如何在C#中匹配XPath查询的XML文件中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道是否有使用C#的方式使我匹配给定的XPath查询XML文件中返回所有的内在价值。
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.
让我们假设我们有一个名为exampleWithFruits.xml下面的XML文件:
Let's suppose that we have the following Xml file named exampleWithFruits.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}
要总结,我想知道如何创建一个函数,如 interestingFunction
To sum up, I would like to know how to create a function such as interestingFunction
THX
推荐答案
一个做到这一点的方法是使用 System.Xml.XPath.Extensions.XPathEvaluate
。
One way to do this is to use 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:
Or if you prefer XmlDocument:
var doc = new XmlDocument();
doc.Load(xmlFilePath);
string[] matchingValues = doc.SelectNodes(xPathQuery).Cast<XmlAttribute>().Select(x => x.Value).ToArray();
这篇关于如何在C#中匹配XPath查询的XML文件中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文