简体   繁体   English

XPath表达式评估错误

[英]XPath expression evaluation error

I try to parse a large XML file and I'm using a lot of relative path for the XPath expressions. 我尝试解析一个大的XML文件,我正在使用很多相对路径的XPath表达式。

Now I'm running into a trouble with the .net XPath evaluation. 现在我遇到了.net XPath评估的麻烦。

Here a small example which explains my problem: 这是一个解释我问题的小例子:

<?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>

And here is the code: 以下是代码:

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

I get the following error message: Additional information: '//price/..[year='2005']' has an invalid token. 我收到以下错误消息:附加信息:'//price /.. [year ='2005']'有一个无效的令牌。

For me, it seems to be a valid XPath expression, since other tools like XMLSpy evaluate that expression successfully. 对我来说,它似乎是一个有效的XPath表达式,因为像XMLSpy这样的其他工具会成功地评估该表达式。

Why not use linq2xml 为什么不使用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

If you want the xpath version,here it is 如果你想要xpath版本,就在这里

"bookstore/book[year='2005']/*/../price"
//gets the price of the books published in 2005

If you look at the XPath spec at http://www.w3.org/TR/xpath/#NT-Step we can see that the Step production is defined as: 如果您查看http://www.w3.org/TR/xpath/#NT-Step上的XPath规范,我们可以看到Step生产定义为:

Step  ::=  AxisSpecifier NodeTest Predicate*    
         | AbbreviatedStep

In other words, a predicate can not follow an abbreviated step, such as . 换句话说,谓词不能遵循缩写步骤,例如。 or .. I would assume that the implementation is therefore (strictly) correct. 或者......我认为实施是(严格地)正确的。 Perhaps XMLSpy is a bit more liberal in its interpretation and simply always expands .. to parent:node()? 也许XMLSpy在解释上有点自由,只是总是扩展到parent:node()?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM