2

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

Eugene Yu
  • 3,708
  • 4
  • 21
  • 27

1 Answers1

1

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.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • Thank you for the answer. but what I need to extract from the tag is 'getNewTokenResponse'. It can be 'deleteTokenResponse' or 'modifyTokenResponse' or something. So I can store them into an attribute as a string.... :D – Eugene Yu Jan 21 '13 at 01:32
  • @EugeneYu I'm sorry I somehow overlooked your comment. If the node beneath the `Body` element can vary, then you can select it using the XPath `/env:Envelope/env:Body/*` instead of the XPath I showed above. – JLRishe Feb 08 '13 at 17:25