2012-10-18 113 views
1

我想知道是否有一種使用C#的方法,它使我能夠返回匹配給定XPath查詢的XML文件中的所有內部值。如何從匹配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} 

綜上所述,我想知道如何創建一個功能如有趣功能

Thx

回答

1

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

E.g.

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

我在哪裏可以找到System.Xml.XPath.Extensions.XPathEvaluate? – Pamplemousse

+0

@Pamplemousse添加對程序集的引用System.Xml.Linq.dll – Fung

+0

添加System.Xml.Linq後,我可以添加System.Xml.XPath.Extensions,但不添加System.Xml.XPath.Extensions.XPathEvaluate。 dll程序集引用。 – Pamplemousse