相关疑难解决方法(0)

XPath:有没有办法为查询设置默认命名空间?

有没有办法将Java的XPath设置为表达式的默认名称空间前缀?例如,代替:/ html:html/html:head/html:title/text()",查询可以是:/ html/head/title/text()

使用命名空间前缀时,必须有一种更优雅的方式.

我现在正在做的示例代码片段:

Node node = ... // DOM of a HTML document
XPath xpath = XPathFactory.newInstance().newXPath();

// set to a NamespaceContext that simply returns the prefix "html"
// and namespace URI ""http://www.w3.org/1999/xhtml"
xpath.setNamespaceContext(new HTMLNameSpace());

String expression = "/html:html/html:head/html:title/text()";
String value = xpath.evaluate(query, expression);
Run Code Online (Sandbox Code Playgroud)

java xpath

12
推荐指数
1
解决办法
6363
查看次数

XPath使用defaultNamespace为xml返回null

我相信它在不久前工作但现在xpath返回null.有人可以帮我在下面的代码中找到我的愚蠢错误吗?
或者我甚至必须在setNamespaceAware(false)之后提供NamespaceContext?

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(false);
domFactory.setIgnoringComments(true);
domFactory.setIgnoringElementContentWhitespace(true);

try {
 Document doc = domFactory.newDocumentBuilder().parse(new File("E:/Temp/test.xml"));
 XPath xp = XPathFactory.newInstance().newXPath();
 NodeList nl = (NodeList) xp.evaluate("//class", doc, XPathConstants.NODESET);
 System.out.println(nl.getLength());
}catch (Exception e){
 e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

XML文档在这里:

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="http://www.example.com/schema">
 <class />
 <class />
</root>
Run Code Online (Sandbox Code Playgroud)

java xpath

3
推荐指数
1
解决办法
1924
查看次数

标签 统计

java ×2

xpath ×2