2010-02-24 165 views
4

嗨給出下面的代碼:XPath查詢不返回結果

private void extractLink(ScriptFile file) throws SAXException, IOException, 
    ParserConfigurationException, XPathExpressionException { 
    Document d = this.parseFile(file); 
    XPathFactory xpf = XPathFactory.newInstance(); 
    XPath xpath = xpf.newXPath(); 
    XPathExpression expr = xpath.compile("//link"); 
    Object result = expr.evaluate(d, XPathConstants.NODE); 
    Node node = (Node) result; 
    if(result!=null) 
    { 
    this.log.debug("Links found: "+node.toString()); 
    } 
    else 
    { 
    this.log.debug("No link found!"); 
    } 
} 

private Document parseFile(ScriptFile file) throws SAXException, IOException, ParserConfigurationException 
{ 
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
    dbf.setValidating(false); 
    dbf.setNamespaceAware(true); 
    dbf.setIgnoringComments(true); 
    dbf.setIgnoringElementContentWhitespace(false); 
    dbf.setExpandEntityReferences(false); 
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); 
    DocumentBuilder db = dbf.newDocumentBuilder(); 
    return db.parse(new ByteArrayInputStream(file.getFile())); 
} 

而且像輸入:

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
<head profile="http://selenium-ide.openqa.org/profiles/test-case"> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
<link rel="selenium.base" href="" /> 
<title>Default-Config-Accounts</title> 
</head> 
<body> 
</body> 
</html> 

爲什麼我的查詢返回NULL?

回答

2

我對Java一般都不熟悉,但是由於代碼中缺少(對我來說)命名空間處理,所以引起了我的XPath懷疑。從您的輸入中,標籤位於默認名稱空間「http://www.w3.org/1999/xhtml」中,所以我希望您必須編寫一些代碼,以告知Java XPath設備這個名稱空間。

有一點谷歌搜索發現這個有用的博客條目XPath with namespaces in Java這看起來像它會解決你的問題。

+0

謝謝丹!你是對的。這是一個命名空間問題。博客文章解決了我的問題。 – er4z0r 2010-02-24 17:09:40

+0

+1。它始終是一個命名空間問題...... XML命名空間永遠不會令人驚訝。顯然,他們被淘汰爲「我不需要關心的另一個屬性」。 – Tomalak 2010-02-26 12:42:39