Parsing xml that has different namespaces using XPath in JAVA

前端 未结 1 902
心在旅途
心在旅途 2020-12-21 13:30

I\'m doing this small project and my task was to read a xml file and parse it so that it can be stored in a class. Here\'s the xml example. it\'s written in SOAP and what I

相关标签:
1条回答
  • 2020-12-21 13:51

    To do an XPath query with namespaces in Java, I believe you need to do something like this:

    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(new NamespaceContext() {
        @Override
        public String getNamespaceURI(String prefix) {
            switch (prefix) {
                case "env":
                    return "http://schemas.xmlsoap.org/soap/envelope/";
                case "ns2":
                    return "http://abc.examples.com/";
            }
    
            return XMLConstants.NULL_NS_URI;
        }
    
        @Override
        public String getPrefix(String namespaceURI) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    
        @Override
        public Iterator getPrefixes(String namespaceURI) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    });
    
    Node getNewTokenResp = 
         (Node) xpath.evaluate("/env:Envelope/env:Body/ns2:getNewTokenResponse", 
         document, XPathConstants.NODE);
    

    You also need to call .setNamespaceAware(true); on your DocumentBuilderFactory before you create the DocumentBuilder to parse your document.

    0 讨论(0)
提交回复
热议问题