XPath:有没有办法为查询设置默认命名空间? [英] XPath: Is there a way to set a default namespace for queries?

查看:110
本文介绍了XPath:有没有办法为查询设置默认命名空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to set Java's XPath to have a default namespace prefix for expressons? For example, instead of: /html:html/html:head/html:title/text()", the query could be: /html/head/title/text()

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

While using the namespace prefix works, there has to be a more elegant way.

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

Sample code snippet of what I'm doing now:

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);


推荐答案

不幸的是,没有。几年前有一些关于为 JxPath 定义默认命名空间的讨论,但很快看看最新的文档并不表示发生了什么事。但是,您可能希望花更多时间查看文档。

Unfortunately, no. There was some talk about defining a default namespace for JxPath a few years ago, but a quick look at the latest docs don't indicate that anything happened. You might want to spends some more time looking through the docs, though.

如果您真的不关心名称空间,那么您可以做的一件事就是解析没有他们的文件。只需忽略您当前正在进行的调用 DocumentBuilderFactory.setNamespaceAware()

One thing that you could do, if you really don't care about namespaces, is to parse the document without them. Simply omit the call that you're currently making to DocumentBuilderFactory.setNamespaceAware().

另外,请注意您的前缀可以是您想要的任何内容;它不必匹配实例文档中的前缀。所以你可以使用 h 而不是 html ,并尽量减少前缀的视觉混乱。

Also, note that your prefix can be anything you want; it doesn't have to match the prefix in the instance document. So you could use h rather than html, and minimize the visual clutter of the prefix.

这篇关于XPath:有没有办法为查询设置默认命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆