Camel

Splitting XML with Camel

XML is one of the most used payloads in enterprise integrations. In this tutorial we will show how you can use Camel's support for splitting an XML file using XPath support and process fragments individually.

Let's take this XML example named books.xml:

<catalog>
   <book id="id100">
      <author age="44">John Smith</author>
      <title>Java Developer's Guide</title>
      <genre>Computer</genre>
      <price>11.95</price>
   </book>
   <book id="id101">
      <author age="24">Sally Joy</author>
      <title>A tale</title>
      <genre>Fantasy</genre>
      <price>1.95</price>
   </book>
</catalog>

We want to show how you can gather information such as the author name:

package com.sample;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;

 
public class XMLCamel {
    
    public static void main(String[] args) throws Exception {
        Main main = new Main();
        main.enableHangupSupport();
        main.addRouteBuilder(new SampleRoute());
        main.run(args);
    }
}

class SampleRoute  extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        System.out.println("My Routing Started");
        from("file:/usr/data/files?noop=true")
            .split(xpath("//catalog/book/author/text()")).to("stream:out"); 
       
    }
}

The above Camel route will print the author names according to the XPath query: //catalog/book/author/text()

The authors will be sent to the Stream.out so you will see them on the console once you run the code.

Result:

John Smith Sally Joy

Let's see a more complex XPath expression:

class SampleRoute  extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        System.out.println("My Routing Started");
        from("file:C:\\data\\jboss?noop=true")                
        .split(xpath("//catalog/book[@id='id100']/author/text()")).to("stream:out"); 
          
        System.out.println("My Routing complete");
    }
}

In the above example, we will restrict the search to authors whose id matches with 'id100'

Result:

John Smit

You can also apply maths on the elements contained in the XML. Let's pickup just authors over 40:

class SampleRoute  extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        System.out.println("My Routing Started");
        from("file:C:\\data\\jboss?noop=true")
                  .split(xpath("//catalog/book/author[@age<40]/text()")).to("stream:out"); 
        System.out.println("My Routing complete");
    }
}

Result:

Sally Joy

Follow us on Twitter