Apache Camel XPath with nodelist

我的梦境 提交于 2019-12-14 02:05:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!