Java – XPath: is there any way to set the default namespace for queries?

Is there any way to set Java XPath as the default namespace prefix? For example, instead of: / HTML: HTML / HTML: head / HTML: title / text() ", the query can be: / HTML / head / Title / text

There must be a more elegant way to use namespace prefixes

Sample code snippet 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);

Solution

Unfortunately, No A few years ago, there was some discussion about defining a default namespace for jxpath, but a quick browse of the latest documents does not mean what happened However, you may want to spend more time browsing documents

One thing you can do, if you really don't care about namespaces, is to parse documents without them Just omit your current call documentbuilderfactory setNamespaceAware().

Also note that your prefix can be anything you want; It does not have to match the prefix in the instance document So you can use h instead of HTML and minimize the visual confusion of prefixes

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>