我尝试解析一个大的 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>
代码如下:
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);
}
我收到以下错误消息: 附加信息:'//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
如果你想要xpath版本,就在这里
"bookstore/book[year='2005']/*/../price"
//gets the price of the books published in 2005
关于c# - XPath 表达式求值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13013401/