How can I make JDOM / XPath ignore namespaces?

I need to process an XML DOM, preferably with a JDOM, where I can do XPath lookups on nodes. I know the names or paths of the node, but I want to ignore the namespaces completely , because sometimes the document comes with namespaces, sometimes without it, and I cannot rely on certain values. Is it possible? How?

+4
source share
4 answers

I know this question is a bit outdated, but for those who will consider this later, you can override several default JDOM classes to effectively ignore namespaces. You can pass your own JDOMFactory implementation to SAXBuilder, which ignores all namespace values โ€‹โ€‹passed to it.

Then override the SAXBuilder class and implement the createContentHandler method to return a SAXHandler with an empty startPrefixMapping method definition.

I did not use this in production setup, so I caution emptor, but I confirmed that it works on some quick and dirty XML materials that I made.

+3
source
/ns:foo/ns:bar/@baz 

becomes

 /*[local-name() = 'foo']/*[local-name() = 'bar']/@baz 

You understand. Do not expect it to be lightning fast.

+17
source

You can use /*:foo (XPath 2.0 or higher) or /yournamespace:* as described here .

The first option selects all nodes with a matching name, regardless of which namespace belongs, including without a namespace. The latter selects all nodes belonging to a particular namespace, regardless of the name of the node.

+3
source

Here is the jDOM2 solution, working in a production installation for a year without problems.

 public class JdomHelper { private static final SAXHandlerFactory FACTORY = new SAXHandlerFactory() { @Override public SAXHandler createSAXHandler(JDOMFactory factory) { return new SAXHandler() { @Override public void startElement( String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { super.startElement("", localName, qName, atts); } @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { return; } }; } }; /** Get a {@code SAXBuilder} that ignores namespaces. * Any namespaces present in the xml input to this builder will be omitted from the resulting {@code Document}. */ public static SAXBuilder getSAXBuilder() { // Note: SAXBuilder is NOT thread-safe, so we instantiate a new one for every call. SAXBuilder saxBuilder = new SAXBuilder(); saxBuilder.setSAXHandlerFactory(FACTORY); return saxBuilder; } } 
+2
source

Source: https://habr.com/ru/post/1306474/


All Articles