Camel Apache:xpath从收到的XML中提取一些值

ops*_*alj 4 xpath apache-camel

在我的Camel路由期间,我查询服务器(HTTP GET),结果,我收到一个200 OK,其XML体看起来像这样:

<?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>
Run Code Online (Sandbox Code Playgroud)

知道我如何能够在XML部分(在我的示例'data2'中)获取"parameter2"的值并将该值存储在交换属性中?我想通过使用xpath表达式?或者......谢谢你的帮助.

Oli*_*ger 9

检索值的简单方法是使用XPath语言.它将允许您提取所需的数据并将其设置在某个位置(标题,正文,...).以下是如何使用以下值设置parameter2标头:

<setHeader headerName="parameter2">
  <xpath resultType="java.lang.String">
    /userProfiles/userProfile/userProfileAttributes/userProfileAttribute[2]/@value
  </xpath>
</setHeader>
Run Code Online (Sandbox Code Playgroud)

使用Java DSL

使用Java DSL并设置消息正文的示例:

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(...);
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考:由于上面的XML包含命名空间,我首先需要在CAMEL路由中定义该命名空间.然后,在通过XPath从XML中提取数据时引用它.因此,在上面的示例中:命名空间ns = new命名空间("contextinfo","http://www.mycompany.com/AEContext/xmldata")以及稍后,使用类似于:ns.xpath("// contextinfo: userProfileAttribute [@ name ='subscriberName']/@ value",String.class). (2认同)