我尝试解析一个大的XML文件,我正在使用很多相对路径的XPath表达式.
现在我遇到了.net XPath评估的麻烦.
这是一个解释我问题的小例子:
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
</book>
</bookstore>
Run Code Online (Sandbox Code Playgroud)
以下是代码:
static void Main(string[] args)
{
System.Xml.XmlDocument d = new System.Xml.XmlDocument();
d.Load(@"D:\simpleXml.xml");
System.Diagnostics.Trace.WriteLine(d.SelectSingleNode("//price/..[year=\'2005\']").Name);
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误消息:附加信息:'//price /.. [year ='2005']'有一个无效的令牌.
对我来说,它似乎是一个有效的XPath表达式,因为像XMLSpy这样的其他工具会成功地评估该表达式.
为什么不使用linq2xml
XDocument doc=XDocument.Load("yourXML");
var bookPrice=doc.Descendants("book")
.Where(x=>x.Element("year").Value=="2005")
.Select(y=>y.Element("price").Value);
//gets the price of the books published in 2005
Run Code Online (Sandbox Code Playgroud)
如果你想要 xpath 版本,这里是
"bookstore/book[year='2005']/*/../price"
//gets the price of the books published in 2005
Run Code Online (Sandbox Code Playgroud)