<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<ParentNode xmlns="http://namespace">
<Status>Some_status</Satus>
<Data>
<Row>Some_row_data</Row>
</Data>
</ParentNode>
</soap:Body>
</soap:Envelope>
A SOAP message similar in structure to the above is produced in an API call
SOAPMessage soapMessage = getSoapMessage()
What I want to do is to be able to run xPath queries on top of my sope message, i.e. I'd like to get the data in the Row node.
What I've done:
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
xPath.setNamespaceContext(new NamespaceContext() {
@Override
public String getNamespaceURI(String prefix) {
return "http://namespace";
}
@Override
public String getPrefix(String namespaceURI) {
return null;
}
@Override
public Iterator getPrefixes(String namespaceURI) {
System.out.println(namespaceURI);
return null;
}
});
SOAPBody body = soapMessage.getSoapBody();
Document document = body.extractContentAsDocument();
NodeList list = (NodeList)xPath.compile("/").evaluate(document, XPathConstants.NODESET);
Node node = list.item(0);
System.out.println(node.getFirstChild().getNodeName());
Running this on the root node is all well and good, ParentNode gets printed to the console.
However, setting replacing my xPath evaluation with the following:
NodeList list = (NodeList)xPath.compile("/ParentNode").evaluate(document, XPathConstants.NODESET);
results in an empty list. I assumed it had something to do with namespaces so I replaced my query with the following:
NodeList list = (NodeList)xPath.compile("/*[name()='ParentNode']").evaluate(document, XPathConstants.NODESET);
and this seems to work ok. My question is, how do I properly set the namespace context so that I can use xPath querying without the name()=... surrounding every node? Do I need to use a DocumentBuilder factory and set its namespace aware to true? If so, how do I feed this SOAP message into that factory?
xPath.compile("/whatever:ParentNode")? – har07 Sep 30 '16 at 22:25