问题
I would like to concatenate all values from the Apache Camel XPath result and add it to the message context. The header should look like: "|value1|value2|valueN|"
My route looks like:
from("direct:test")
.setHeader("key").xpath("//Identifier", List.class)
.to("mock:result")
What is the best way for doing that? Is there a way to implement an own result type?
Thanks
回答1:
As Willem said, you have to write your own processor.
For such a little thing, my favourite way is to declare a function in the class containing the route definition returning an anonymous Processor like this:
private Processor setHeaderWithIdentifiers() {
return new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
List<String> identifiers = new ArrayList<>();
NodeList nodes = XPathBuilder.xpath("//Identifier").evaluate(exchange, NodeList.class);
for (int i = 0; i < nodes.getLength(); i++) {
identifiers.add(nodes.item(i).getNodeValue());
}
// StringUtils from Apache Commons 3
String idAsString = StringUtils.join(identifiers, "|");
exchange.getIn().setHeader("key", idAsString);
}
};
}
With that, you do not need to find any complex Xpath functions and the code remains clear to understand as long the Processor code remains short.
来源:https://stackoverflow.com/questions/20529197/apache-camel-xpath-with-nodelist