2012-10-22 87 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()?