Extract term from SOAP header using Xpath

I would like to extract an element called ServiceGroupID from the SOAP header that defines the transaction session. I will need this so that I can forward the request to the same server using a SOAP session. My XML is as follows:

<?xml version="1.0" encoding="http://schemas.xmlsoap.org/soap/envelope/" standalone="no"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">
<wsa:ReplyTo>
<wsa:Address>http://www.w3.org/2005/08/addressing/none</wsa:Address>
<wsa:ReferenceParameters>
<axis2:ServiceGroupId xmlns:axis2="http://ws.apache.org/namespaces/axis2">urn:uuid:99A029EBBC70DBEB221347349722532</axis2:ServiceGroupId>
</wsa:ReferenceParameters>
</wsa:ReplyTo>
<wsa:MessageID>urn:uuid:99A029EBBC70DBEB221347349722564</wsa:MessageID>
<wsa:Action>Perform some action</wsa:Action>
<wsa:RelatesTo>urn:uuid:63AD67826AA44DAE8C1347349721356</wsa:RelatesTo>
</soapenv:Header>

I would like to know how I can extract the Session GroupId from the above XML using Xpath.

Any help would be greatly appreciated.

+5
source share
1 answer

You did not specify the technology, therefore, assuming you have not configured the equivalent of the .NET NameSpace Manager or similar, you can use the namespace agnostic Xpath as follows:

/*[local-name()='Envelope']/*[local-name()='Header']
      /*[local-name()='ReplyTo']/*[local-name()='ReferenceParameters']
      /*[local-name()='ServiceGroupId']/text()

Change Updated for Java

XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expression = xpath.compile("/*[local-name()='Envelope']/*[local-name()='Header']/*[local-name()='ReplyTo']/*[local-name()='ReferenceParameters']/*[local-name()='ServiceGroupId']/text()");
System.out.println(expression.evaluate(myXml));

NamespaceContext

NamespaceContext context = new NamespaceContextMap(
    "soapenv", "http://schemas.xmlsoap.org/soap/envelope/", 
    "wsa", "http://www.w3.org/2005/08/addressing",
    "axis2", "http://ws.apache.org/namespaces/axis2");
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
xpath.setNamespaceContext(context);
XPathExpression expression = xpath.compile("/soapenv:Envelope/soapenv:Header/wsa:ReplyTo/wsa:ReferenceParameters/axis2:Serv‌​iceGroupId/text()");
System.out.println(expression.evaluate(myXml));

local-name() . , encoding XML- .

Edit

, urn:uuid: , XPath 9 ( XPath). urn:uuid , tokenize/split .., .

substring(string(/*[local-name()='Envelope']/*[local-name()='Header']
                 /*[local-name()='ReplyTo']/*[local-name()='ReferenceParameters']
                 /*[local-name()='ServiceGroupId']/text()), 10)
+6

All Articles