Eugene Yu
Eugene Yu

Reputation: 3958

Parsing xml that has different namespaces using XPath in JAVA

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 want to do is get

<ns2:getNewTokenResponse xmlns:ns2="http://abc.examples.com/">

this part parsed and the child nodes so that I can create a class that has 'nodeName' as an attribute with a value of 'getNewTokenResponse'. +session key

<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>
    <env:Header>
    </env:Header>
    <env:Body>
        <ns2:getNewTokenResponse xmlns:ns2="http://abc.examples.com/">
            <return>
                {{session.key}}
            </return>
        </ns2:getNewTokenResponse>
    </env:Body>
</env:Envelope>

But my real problem is, I found many good example codes, namespaces are not prefixed and structure of xml file can vary. So here I am being confused to achieve the task. I'll appreciate any advice. Cheers:D

Upvotes: 2

Views: 3038

Answers (1)

JLRishe
JLRishe

Reputation: 101680

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.

Upvotes: 1

Related Questions