Reading an XML file

In this recipe, you'll learn to read an XML file as part of a read/process/write step.

Getting ready

We'll read this XML file:

<?xml version="1.0" encoding="UTF-8"?>
<records>
    <person>
        <firstName>Shania</firstName>
    <age>49</age>
    </person>
    <person>
        <firstName>Nelly</firstName>
    <age>36</age>
    </person>
</records>

For each person's record in the XML file, a User object will be created. Make sure that the User class exists:

public class User {
  private String firstName;
  private int age;

How to do it…

To parse the XML file, use StaxEventItemReader, which is provided by Spring Batch. To generate User objects, use XStreamMarshaller, a class from the Spring Object/XML Mapping project. Follow these steps:

  1. Add the Maven dependency for Spring Object/XML ...

Get Spring Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.