2013-12-21 58 views
1

我有jdom2 XPath的問題:與jdom2 XPath查詢結果不明

test.xhtml代碼:

<?xml version="1.0" encoding="utf-8"?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="cs" lang="cs"> 
<head> 
<title>mypage</title> 
</head> 
<body> 
<div class="in"> 
<a class="nextpage" href="url.html"> 
<img src="img/url.gif" alt="to url.html" /> 
</a> 
</div> 
</body> 
</html> 

Java代碼:

Document document; 
SAXBuilder saxBuilder = new SAXBuilder(); 

document = saxBuilder.build("test2.html"); 
XPathFactory xpfac = XPathFactory.instance(); 
XPathExpression<Element> xp = xpfac.compile("//a[@class = 'nextpage']", Filters.element()); 
for (Element att : xp.evaluate(document)) { 
    System.out.println("We have target " + att.getAttributeValue("href")); 
} 

但只是這個我不能得到任何元素。我發現當查詢是//*[@class = 'nextpage']時,它發現它。

We have target url.html 

它必須是一些與命名空間或以其他任何標題,因爲沒有它,它可以產生一些輸出。我不知道我做錯了什麼。

+0

「它必須是具有名稱空間的東西」 - 正確。我已經鏈接到的「可能重複」問題是谷歌給我的第一個命令「jdom xpath namespace」 –

+0

現在似乎已經解決 - changes:Namespace namespace = Namespace.getNamespace(「my」,「http://www.w3 .ORG/1999/XHTML「);和XPathExpression xp = xpfac.compile(「// my:a [@class ='nextpage']」,Filters.element(),null,namespace); – d3im

+1

這個問題似乎是脫離主題,因爲它現在已經_solved_(見OP的評論)。 – devnull

回答

0

注意:儘管這與建議的重複項中描述的問題相同,但其他問題與JDOM版本1.x有關。在JDOM 2.x中有很多重要的區別。這個答案與JDOM 2.x XPath實現which is significantly different有關。

XPath規範非常清楚如何在XPath表達式中處理名稱空間。不幸的是,對於熟悉XML的人來說,命名空間的XPath處理與他們的期望略有不同。 This is the specification

節點測試中的QName使用來自表達式上下文的名稱空間聲明擴展爲擴展名。這與擴展在開始和結束標籤中的元素類型名稱的擴展方式相同,只是不使用用xmlns聲明的默認名稱空間:如果QName沒有前綴,則名稱空間URI爲null(這是相同的方式屬性名稱被擴展)。如果QName的前綴沒有在表達式上下文中存在名稱空間聲明,那是錯誤的。

實際上,這意味着,只要在XML文檔中有'默認'命名空間,在XPath表達式中使用該命名空間時,仍然需要爲該名稱空間添加前綴。 XPathFactory.compile(...)方法暗示了這個要求in the JavaDoc,但它不像它應該那樣清晰。您使用的前綴是任意的,並且僅限於該XPath表達式的本地。在你的情況下,代碼會看起來像(假設我們選擇的命名空間xhtml的URI http://www.w3.org/1999/xhtml):

XPathFactory xpfac = XPathFactory.instance(); 
Namespace xhtml = Namespace.getNamespace("xhtml", "http://www.w3.org/1999/xhtml"); 
XPathExpression<Element> xp = xpfac.compile("//xhtml:a[@class = 'nextpage']", Filters.element(), null, xhtml); 
for (Element att : xp.evaluate(document)) { 
    System.out.println("We have target " + att.getAttributeValue("href")); 
} 

我應該將其添加到常見問題解答...謝謝。