Wednesday, July 27, 2016

[WSO2 ESB] Retrieving values from a payload excluding namespaces into a property.

Assume that we want to retrieve some elements from the payload excluding the namespaces.
We can do this in different ways.

1. If it is a payload defined by ourselves, we can define the payload with an empty namespace.

EX:

<Entries xmlns= "">
                 <Entry>
                    <name>Olivia</name>
                    <userId>1</userId>
        <age>25</age>
                 </Entry>
</Entries>

And we can write a XPATH expression to retrieve the required element into a property like this.

<property name="nameOfThePerson" expression="//Entries/Entry/name"/>

2. If it is a payload we are getting from an outside source, and it contains a namespace defined in the payload.

Here we have to define the namespace reference in our property mediator like this to retrieve only the value of the element without the namespace.

EX:

If the payload we are getting is like this,

<Entries xmlns= "http://wso2.samples.com">
                 <Entry>
                    <name>Olivia</name>
                    <userId>1</userId>
        <age>25</age>
                 </Entry>
</Entries>

And if we want to retrieve the value of the age element into a property.
This can be done in two ways,

i.) We can define the property with a reference to the namespace like this,

<property xmlns:ns="http://wso2.samples.com"
                  name="age"
                  expression="//ns:Entries/ns:Entry/ns:age"/>

ii.) This can be done without defining the namespace in property like this.

        <property name="age" expression="//*[local-name()='age']"/>

This expression will also retrieve the same age value. And here you don’t want to add the namespace reference. So it becomes much more simpler and clearer than the previous one.

Sample proxy service

<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse" name="removeNameSpaces" transports="https,http" statistics="disable" trace="disable" startOnLoad="true">
   <target>
      <inSequence>
         <payloadFactory media-type="xml">
            <format>
               <Entries xmlns="http://wso2.samples.com">
                  <Entry>
                     <name>Olivia</name>
                     <userId>1</userId>
                     <age>25</age>
                  </Entry>
               </Entries>
            </format>
            <args />
         </payloadFactory>
         <property xmlns:ns="http://wso2.samples.com" name="age" expression="//ns:Entries/ns:Entry/ns:age" />
         <property name="userId" expression="//*[local-name()='userId']" />
         <log level="custom">
            <property name="age" expression="get-property('age')" />
            <property name="userId" expression="get-property('userId')" />
         </log>
      </inSequence>
   </target>
   <description />
</proxy>
                               
Sample output


No comments:

Post a Comment