Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 200
opstalj Avatar asked Jan 17 '23 06:01

opstalj


1 Answers

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(...);
like image 91
Olivier.Roger Avatar answered May 09 '23 14:05

Olivier.Roger