How to split and search through an XML file 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:

<?xml version="1.0" encoding="UTF-8"?><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.mastertheboss.camel;
import org.apache.camel.main.Main;
public class MainApp {
  public static void main(String...args) throws Exception {
    // use Camels Main class         
    Main main = new Main();
    main.addRouteBuilder(MyRouteBuilder.class);
    main.run(args);
  }
}
package com.mastertheboss.camel;
import org.apache.camel.builder.RouteBuilder;
public class MyRouteBuilder extends RouteBuilder {
  public void configure() {
    from("file:src/data?noop=true").split(xpath("//catalog/book/author/text()")).to("log:output");
  }
}

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 log output 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:

package com.mastertheboss.camel;

import org.apache.camel.builder.RouteBuilder;

public class MyRouteBuilder2 extends RouteBuilder {
  public void configure() {
    from("file:src/data?noop=true")
        .split(xpath("//catalog/book[@id='id100']/author/text()"))
        .to("log:output");
  }
}

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

Result:

John Smith

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

package com.mastertheboss.camel;

import org.apache.camel.builder.RouteBuilder;

public class MyRouteBuilder3 extends RouteBuilder {
  public void configure() {
    from("file:src/data?noop=true")
        .split(xpath("//catalog/book/author[@age<40]/text()"))
        .to("log:output");
  }
}

Result:

Sally Joy

Source code: https://github.com/fmarchioni/masterspringboot/tree/master/camel/camel-split-xml