opstalj
opstalj

Reputation: 900

Camel Apache: xpath to extract some value out of received XML

during my Camel routes, I query a server (a HTTP GET) and as a result, I receive a 200 OK with a XML body looking similar like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<userProfiles xmlns="http://www.mycompany.com/AEContext/xmldata">
  <userProfile name="guest">
    <userProfileAttributes>
      <userProfileAttribute name="parameter1" value="data1" nameVisibility="ALL"/>  
      <userProfileAttribute name="parameter2" value="data2" nameVisibility="ALL"/>
      <userProfileAttribute name="parameter3" value="data3" nameVisibility="ALL"/>
    </userProfileAttributes>
  </userProfile>
</userProfiles>

Any idea how I would be able to get the value of "parameter2" in the XML part (in my example 'data2') and store that value in an exchange property ? I guess by using an xpath expression ? Or ... Thanks for your help.

Upvotes: 5

Views: 21957

Answers (1)

Olivier.Roger
Olivier.Roger

Reputation: 4249

An easy way to retrieve the value would be to use the XPath Language. It will allow you to extract the data you want and set it somewhere (header, body , ...). Here is how to set a parameter2 header with the value:

<setHeader headerName="parameter2">
  <xpath resultType="java.lang.String">
    /userProfiles/userProfile/userProfileAttributes/userProfileAttribute[2]/@value
  </xpath>
</setHeader>

Using Java DSL

An example using the Java DSL and setting the message body:

final Namespaces ns = new Namespaces("c", "http://www.mycompany.com/AEContext/xmldata");

// existing code
from(...)
  .setBody(
    ns.xpath(
      "/c:userProfiles/userProfile/userProfileAttributes/userProfileAttribute[2]/@value",   
      String.class)
   )
   .to(...);

Upvotes: 10

Related Questions