2010-02-24 168 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