2012-10-22 88 views
5

我尝试解析一个大的XML文件,并且我使用了很多XPath表达式的相对路径。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); 
} 

我收到以下错误信息: 附加信息:“//价格/。 。[year ='2005']'有一个无效的标记。

对我来说,它似乎是一个有效的XPath表达式,因为像XMLSpy这样的其他工具可以成功评估表达式。

+4

.NET不支持XPath 2.0。 –

+0

@MatíasFidemraizer说明了很多,谢谢 – exagi

+0

如果年前来价格你可以使用'/ /价格[先前 - 兄弟::年= 2005']。 – Pawel

回答

1

为什么不使用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 
0

如果你看看XPath的规范在http://www.w3.org/TR/xpath/#NT-Step我们可以看到,步骤生产被定义为:

Step ::= AxisSpecifier NodeTest Predicate*  
     | AbbreviatedStep 

In oth呃言之,一个谓词不能遵循一个简短的步骤,比如。或者..我会认为实施是(严格)正确的。也许XMLSpy在其解释中更加自由一些,并且总是将其展开为parent:node()?