javax.xml, XPath is not extracted from XML with namespaces

后端 未结 2 688
醉酒成梦
醉酒成梦 2020-12-22 10:52

There is \"original\" XML


    
        

        
相关标签:
2条回答
  • 2020-12-22 11:39

    You can always do it by ignoring namespace, not the ideal method but works.

     "/*[local-name()='Envelope']/*[local-name()='Header']/*[local-name()='context']/*[local-name()='session']/text()"
    
    0 讨论(0)
  • 2020-12-22 11:41

    The answer is that you need to correctly use namespaces and namespace prefixes:

    First, make your DocumentBuilderFactory namespace aware by calling this before you use it:

    factory.setNamespaceAware(true); 
    

    Then do this to retrieve the value you want:

    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    xpath.setNamespaceContext(new NamespaceContext() {
        @Override
        public String getNamespaceURI(String prefix) {
            if (prefix.equals("soap")) {
                return "http://www.w3.org/2003/05/soap-envelope";
            }
            if (prefix.equals("zmb")) {
                return "urn:zimbra";
            }
    
            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.");
        }
    });
    
    XPathExpression expr = 
           xpath.compile("/soap:Envelope/soap:Header/zmb:context/zmb:session");
    String sessionId = (String)expr.evaluate(doc, XPathConstants.STRING);
    

    You may need to add a line to the beginning of your file to import the NamespaceContext class:

    import javax.xml.namespace.NamespaceContext;
    

    http://ideone.com/X3iX5N

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