Apache Camel / xpath操作结果检测

时间:2012-08-30 14:26:48

标签: xpath apache-camel

给定一个Camel路由,该路由应该提取XML消息的一些内部部分,从中创建一条新消息然后传递它。

 from(SUB_EXTRACT_XML)
   .setExchangePattern(ExchangePattern.InOut)
   .setBody().xpath("//mmsg:MyMessage/mmsg:AnyPayload/*", namespaces) 
   .setBody().simple("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n${in.body}")
   .to(...)

对于像这样的正确输入消息(“嵌入式”xml消息在模式中由xs:any定义),它正在工作,因为消息是我期望的那样:

<mmsg:MyMessage>
  <mmsg:RandomTags/>
   ...
   <mmsg:AnyPayload> <!-- xs:any in xsd -->
     <some><xml/><here/></some>
   </mmsg:AnyPayload>
</mmsg:MyMessage>

鉴于XML消息存在一些问题,例如缺少mmsg:AnyPayload标记,因此XPATH无法完成其工作:

<mmsg:MyMessage>
  <mmsg:RandomTags/>
   ...
   <some><xml/><here/></some>
</mmsg:MyMessage>

XPATH将无法提取数据并传递整个XML消息(包括mmsg:MyMessage),这不是预期的。我宁愿在这个阶段抛出一些例外。

问题:

有没有办法检查xpath表达式是否实际上找到了稍后在路由中引用的元素,或者是否无法提取给定元素?

我知道我之前可以对消息进行一些模式验证并拒绝垃圾邮件,但有没有办法查看XPath表达式是否失败?

1 个答案:

答案 0 :(得分:0)

解决方案是在路由中使用choice() DSL,如下所示:

 from(SUB_EXTRACT_XML)
   .setExchangePattern(ExchangePattern.InOut)
   .choice()
        .when(xpath("//mmsg:MyMessage/mmsg:AnyPayload", namespaces))
            .setHeader("Status", "OK") // just for another example how to transmit some variable between two routes 
            .setBody().simple("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n${in.body}")
            .endChoice()
        .otherwise()
            .log(LoggingLevel.ERROR, "LoggerName", "Error message; Stop the processing")
            .stop()
        .endChoice()
    .end()
   // Just to show the headers are following the route... 
   .to("DIRECT_GO_FORWARD"); 



 from("DIRECT_GO_FORWARD")
   .setExchangePattern(ExchangePattern.InOut)
   .choice()
        .when(header("Status").isEqualTo("OK"))
            .bean(new SampleProcessor())

        ...
    .end()
    ...
    .to("...");

第二条路线就是为了表明你可以使用第一条路线中设置的标题(以及身体)。