How can I get JDOM/XPath to ignore namespaces?

后端 未结 4 1625
轮回少年
轮回少年 2021-01-18 19:35

I need to process an XML DOM, preferably with JDOM, where I can do XPath search on nodes. I know the node names or paths, but I want to ignore namespaces completely<

4条回答
  •  醉酒成梦
    2021-01-18 20:29

    Here is a jDOM2 solution that has been running in a production setting for a year with no trouble.

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

提交回复
热议问题