Friday, February 22, 2013

Extract a value of an XML type attribute using WSO2 ESB

Let's say you have an XML input with some elements as below.

                message="&lt;RegistraionNotificationEvent NotificationType=&quot;Place&quot;>&lt;DeviceLocPlace
                timestamp=&quot;1361210060855&quot; accuracy=&quot;344.0&quot;
                macAddress=&quot;7b:29:a8:8b:e4:f8&quot; lastSeen=&quot;7&quot;
                sourceTimestamp=&quot;1361209904211&quot; x=&quot;171.34&quot; y=&quot;104.513&quot;/>&lt;/RegistraionNotificationEvent>" />

 You need to extract out the macAddress which is inside the message attribute. How can we do that?

If you closely look at this input, you would see, the macAddress stays inside the value of the attribute "message". But this message attribute carries another XML element which comes as a String. 

Now what? 

This is where WSO2 ESB Script mediator comes into rescue.
With just the following piece of configuration, you can extract out the  Mac Address.

<script language="js">
      <![CDATA[mc.setPayloadXML(new XML(mc.getPayloadXML()..*::Notification.@message.toXMLString()));]]></script>

The above segment converts the value of the attribute message into XML.

<property xmlns:ns="http://org.apache.synapse/xsd" name="mac" expression="//@macAddress" scope="default" type="STRING"/>

Using this segment, from the XML obtained above, you can extract out the macAddress part easily.

As handy as that...

No comments:

Post a Comment