Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 Mapping in pom.xml:

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId...