{{announcement.body}}
{{announcement.title}}

Spring Batch — Read From XML

DZone 's Guide to

Spring Batch — Read From XML

In this article, see how to read from XML.

· Database Zone ·
Free Resource

Two purple flowers in a field

In this example, I will show you how to read from XML, and for now, simply print the details on console. However, you can save this XML data into Relational or Non Relational or write it into CSV. I will write other articles to cover such topics.

I have used the latest version of Spring Boot, Spring Batch:

Java
xxxxxxxxxx
1
15
 
1
package com.example;
2
 
          
3
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
4
import org.springframework.boot.SpringApplication;
5
import org.springframework.boot.autoconfigure.SpringBootApplication;
6
 
          
7
@SpringBootApplication
8
@EnableBatchProcessing
9
public class ReadingXmlApplication {
10
 
          
11
    public static void main(String[] args) {
12
        SpringApplication.run(ReadingXmlApplication.class, args);
13
    }
14
}
15
 
          


You might also like: 3 Steps to Writing and Reading XML Files

The below class is responsible for reading the XML file line by line and creating Customer object out of it.

Java
xxxxxxxxxx
1
47
 
1
package com.example.config;
2
 
          
3
import java.time.LocalDateTime;
4
import java.time.format.DateTimeFormatter;
5
 
          
6
import com.example.domain.Customer;
7
import com.thoughtworks.xstream.converters.Converter;
8
import com.thoughtworks.xstream.converters.MarshallingContext;
9
import com.thoughtworks.xstream.converters.UnmarshallingContext;
10
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
11
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
12
 
          
13
public class CustomerConverter implements Converter {
14
    private static final DateTimeFormatter DT_FORMATTER = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
15
    
16
    @Override
17
    public boolean canConvert(Class type) {
18
        return type.equals(Customer.class);
19
    }
20
 
          
21
    @Override
22
    public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
23
        // Don't do anything
24
    }
25
 
          
26
    @Override
27
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
28
        reader.moveDown();
29
        Customer customer = new Customer();
30
        customer.setId(Long.valueOf(reader.getValue()));
31
        
32
        reader.moveUp();
33
        reader.moveDown();
34
        customer.setFirstName(reader.getValue());
35
        
36
        reader.moveUp();
37
        reader.moveDown();
38
        customer.setLastName(reader.getValue());
39
        
40
        reader.moveUp();
41
        reader.moveDown();
42
        customer.setBirthdate(LocalDateTime.parse(reader.getValue(), DT_FORMATTER));
43
        
44
        return customer;
45
    }
46
 
          
47
}


Below is the Configuration class to configure the ItemReader, ItemWriter, and configure step details.

Java
xxxxxxxxxx
1
71
 
1
package com.example.config;
2
 
          
3
import java.util.HashMap;
4
import java.util.Map;
5
 
          
6
import org.springframework.batch.core.Job;
7
import org.springframework.batch.core.Step;
8
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
9
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
10
import org.springframework.batch.item.ItemWriter;
11
import org.springframework.batch.item.xml.StaxEventItemReader;
12
import org.springframework.beans.factory.annotation.Autowired;
13
import org.springframework.context.annotation.Bean;
14
import org.springframework.context.annotation.Configuration;
15
import org.springframework.core.io.ClassPathResource;
16
import org.springframework.oxm.xstream.XStreamMarshaller;
17
 
          
18
import com.example.domain.Customer;
19
 
          
20
@Configuration
21
public class JobConfiguration {
22
    @Autowired
23
    private JobBuilderFactory jobBuilderFactory;
24
    
25
    @Autowired
26
    private StepBuilderFactory stepBuilderFactory;
27
    
28
    @Bean
29
    public StaxEventItemReader<Customer> customerItemReader(){
30
        Map<String, Class> aliases = new HashMap<>();
31
        aliases.put("customer", Customer.class);
32
        
33
        CustomerConverter converter = new CustomerConverter();
34
 
          
35
        XStreamMarshaller ummarshaller = new XStreamMarshaller();
36
        ummarshaller.setAliases(aliases);
37
        ummarshaller.setConverters(converter);
38
        
39
        StaxEventItemReader<Customer> reader = new StaxEventItemReader<>();
40
        reader.setResource(new ClassPathResource("/data/customer.xml"));
41
        reader.setFragmentRootElementName("customer");
42
        reader.setUnmarshaller(ummarshaller);
43
        
44
        return reader;
45
    }
46
    
47
    @Bean
48
    public ItemWriter<Customer> customerItemWriter(){
49
        return items -> {
50
            for (Customer customer : items) {
51
                System.out.println(customer.toString());
52
            }
53
        };
54
    }
55
    
56
    @Bean
57
    public Step step1() {
58
        return stepBuilderFactory.get("step1")
59
                .<Customer, Customer>chunk(10)
60
                .reader(customerItemReader())
61
                .writer(customerItemWriter())
62
                .build();
63
    }
64
    
65
    @Bean
66
    public Job job() {
67
        return jobBuilderFactory.get("job")
68
                .start(step1())
69
                .build();
70
    }
71
}


Model class for Customer.

Java
xxxxxxxxxx
1
22
 
1
package com.example.domain;
2
 
          
3
import java.time.LocalDateTime;
4
 
          
5
import javax.xml.bind.annotation.XmlRootElement;
6
 
          
7
import lombok.AllArgsConstructor;
8
import lombok.Builder;
9
import lombok.Data;
10
import lombok.NoArgsConstructor;
11
 
          
12
@AllArgsConstructor
13
@NoArgsConstructor
14
@Builder
15
@Data
16
@XmlRootElement(name = "Customer")
17
public class Customer {
18
    private Long id;
19
    private String firstName;
20
    private String lastName;
21
    private LocalDateTime birthdate;
22
}


Customer.xml

XML
xxxxxxxxxx
1
75
 
1
<?xml version="1.0" encoding="UTF-8" ?>
2
<customers>
3
    <customer>
4
        <id>1</id>
5
        <firstName>John</firstName>
6
        <lastName>Doe</lastName>
7
        <birthdate>10-10-1988 19:43:23</birthdate>
8
    </customer>
9
    <customer>
10
        <id>2</id>
11
        <firstName>James</firstName>
12
        <lastName>Moss</lastName>
13
        <birthdate>01-04-1991 10:20:23</birthdate>
14
    </customer>
15
    <customer>
16
        <id>3</id>
17
        <firstName>Jonie</firstName>
18
        <lastName>Gamble</lastName>
19
        <birthdate>21-07-1982 11:12:13</birthdate>
20
    </customer>
21
    <customer>
22
        <id>4</id>
23
        <firstName>Mary</firstName>
24
        <lastName>Kline</lastName>
25
        <birthdate>07-08-1973 11:27:42</birthdate>
26
    </customer>
27
    <customer>
28
        <id>5</id>
29
        <firstName>William</firstName>
30
        <lastName>Lockhart</lastName>
31
        <birthdate>04-04-1994 04:15:11</birthdate>
32
    </customer>
33
    <customer>
34
        <id>6</id>
35
        <firstName>John</firstName>
36
        <lastName>Doe</lastName>
37
        <birthdate>10-10-1988 19:43:23</birthdate>
38
    </customer>
39
    <customer>
40
        <id>7</id>
41
        <firstName>Kristi</firstName>
42
        <lastName>Dukes</lastName>
43
        <birthdate>17-09-1983 21:22:23</birthdate>
44
    </customer>
45
    <customer>
46
        <id>8</id>
47
        <firstName>Angel</firstName>
48
        <lastName>Porter</lastName>
49
        <birthdate>15-12-1980 18:09:09</birthdate>
50
    </customer>
51
    <customer>
52
        <id>9</id>
53
        <firstName>Mary</firstName>
54
        <lastName>Johnston</lastName>
55
        <birthdate>07-07-1987 19:43:03</birthdate>
56
    </customer>
57
    <customer>
58
        <id>10</id>
59
        <firstName>Linda</firstName>
60
        <lastName>Rodriguez</lastName>
61
        <birthdate>16-09-1991 09:13:43</birthdate>
62
    </customer>
63
    <customer>
64
        <id>11</id>
65
        <firstName>Phillip</firstName>
66
        <lastName>Lopez</lastName>
67
        <birthdate>18-12-1965 11:10:09</birthdate>
68
    </customer>
69
    <customer>
70
        <id>12</id>
71
        <firstName>Peter</firstName>
72
        <lastName>Dixon</lastName>
73
        <birthdate>09-05-1996 19:09:23</birthdate>
74
    </customer>
75
</customers>


pom.xml

XML
xxxxxxxxxx
1
90
 
1
<?xml version="1.0" encoding="UTF-8"?>
2
<project xmlns="http://maven.apache.org/POM/4.0.0"
3
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5
    <modelVersion>4.0.0</modelVersion>
6
    <p>
7
        <groupId>org.springframework.boot</groupId>
8
        <artifactId>spring-boot-starter-parent</artifactId>
9
        <version>2.2.2.RELEASE</version>
10
        <relativePath ></relativePath> <!-- lookup parent from repository -->
11
    </parent>
12
    <groupId>com.example</groupId>
13
    <artifactId>readingXML</artifactId>
14
    <version>0.0.1-SNAPSHOT</version>
15
    <p>jar</packaging>
16
    <name>readingXML</name>
17
    <description>Demo project for Spring Boot</description>
18
 
          
19
    <p>
20
        <java.version>1.8</java.version>
21
    </properties>
22
 
          
23
    <dependencies>
24
        <!-- Spring Starter Batch -->
25
        <dependency>
26
            <groupId>org.springframework.boot</groupId>
27
            <artifactId>spring-boot-starter-batch</artifactId>
28
        </dependency>
29
 
          
30
        <!-- Spring OXM -->
31
        <dependency>
32
            <groupId>org.springframework</groupId>
33
            <artifactId>spring-oxm</artifactId>
34
        </dependency>
35
 
          
36
        <!-- Spring Starter JDBC -->
37
        <dependency>
38
            <groupId>org.springframework.boot</groupId>
39
            <artifactId>spring-boot-starter-jdbc</artifactId>
40
        </dependency>
41
 
          
42
        <!-- H2 -->
43
        <dependency>
44
            <groupId>com.h2database</groupId>
45
            <artifactId>h2</artifactId>
46
            <scope>runtime</scope>
47
        </dependency>
48
 
          
49
        <!-- MYSQL -->
50
        <dependency>
51
            <groupId>mysql</groupId>
52
            <artifactId>mysql-connector-java</artifactId>
53
            <scope>runtime</scope>
54
        </dependency>
55
        <!-- XSTREAM -->
56
        <dependency>
57
            <groupId>com.thoughtworks.xstream</groupId>
58
            <artifactId>xstream</artifactId>
59
            <version>1.4.7</version>
60
        </dependency>
61
 
          
62
 
          
63
        <!-- Lombok -->
64
        <dependency>
65
            <groupId>org.projectlombok</groupId>
66
            <artifactId>lombok</artifactId>
67
            <version>1.18.2</version>
68
            <optional>true</optional>
69
        </dependency>
70
        <dependency>
71
            <groupId>org.springframework.boot</groupId>
72
            <artifactId>spring-boot-starter-test</artifactId>
73
            <scope>test</scope>
74
        </dependency>
75
        <dependency>
76
            <groupId>org.springframework.batch</groupId>
77
            <artifactId>spring-batch-test</artifactId>
78
            <scope>test</scope>
79
        </dependency>
80
    </dependencies>
81
 
          
82
    <build>
83
        <p>
84
            <p>
85
                <groupId>org.springframework.boot</groupId>
86
                <artifactId>spring-boot-maven-plugin</artifactId>
87
            </plugin>
88
        </plugins>
89
    </build>
90
</project>


Here is the final output:

Java
xxxxxxxxxx
1
35
 
1
 
          
2
  .   ____          _            __ _ _
3
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
4
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
5
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
6
  '  |____| .__|_| |_|_| |_\__, | / / / /
7
 =========|_|==============|___/=/_/_/_/
8
 :: Spring Boot ::        (v2.2.2.RELEASE)
9
 
          
10
2019-12-11 23:17:01.629  INFO 6896 --- [           main] com.example.ReadingXmlApplication        : Starting ReadingXmlApplication on 841DTN2 with PID 6896 (C:\Learnings\Spring_Batch\spring-boot-spring-batch\Spring-Batch-by-Michael-Minella\readingXML\target\classes started by e081155 in C:\Learnings\Spring_Batch\spring-boot-spring-batch\Spring-Batch-by-Michael-Minella\readingXML)
11
2019-12-11 23:17:01.632  INFO 6896 --- [           main] com.example.ReadingXmlApplication        : No active profile set, falling back to default profiles: default
12
2019-12-11 23:17:02.492  INFO 6896 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
13
2019-12-11 23:17:02.765  INFO 6896 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
14
2019-12-11 23:17:02.893  INFO 6896 --- [           main] o.s.b.c.r.s.JobRepositoryFactoryBean     : No database type set, using meta data indicating: H2
15
2019-12-11 23:17:03.084  INFO 6896 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : No TaskExecutor has been set, defaulting to synchronous executor.
16
2019-12-11 23:17:03.171  INFO 6896 --- [           main] com.example.ReadingXmlApplication        : Started ReadingXmlApplication in 2.052 seconds (JVM running for 2.562)
17
2019-12-11 23:17:03.172  INFO 6896 --- [           main] o.s.b.a.b.JobLauncherCommandLineRunner   : Running default command line with: []
18
2019-12-11 23:17:03.236  INFO 6896 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=job]] launched with the following parameters: [{}]
19
2019-12-11 23:17:03.298  INFO 6896 --- [           main] o.s.batch.core.job.SimpleStepHandler     : Executing step: [step1]
20
Customer(id=1, firstName=John, lastName=Doe, birthdate=1988-10-10T19:43:23)
21
Customer(id=2, firstName=James, lastName=Moss, birthdate=1991-04-01T10:20:23)
22
Customer(id=3, firstName=Jonie, lastName=Gamble, birthdate=1982-07-21T11:12:13)
23
Customer(id=4, firstName=Mary, lastName=Kline, birthdate=1973-08-07T11:27:42)
24
Customer(id=5, firstName=William, lastName=Lockhart, birthdate=1994-04-04T04:15:11)
25
Customer(id=6, firstName=John, lastName=Doe, birthdate=1988-10-10T19:43:23)
26
Customer(id=7, firstName=Kristi, lastName=Dukes, birthdate=1983-09-17T21:22:23)
27
Customer(id=8, firstName=Angel, lastName=Porter, birthdate=1980-12-15T18:09:09)
28
Customer(id=9, firstName=Mary, lastName=Johnston, birthdate=1987-07-07T19:43:03)
29
Customer(id=10, firstName=Linda, lastName=Rodriguez, birthdate=1991-09-16T09:13:43)
30
Customer(id=11, firstName=Phillip, lastName=Lopez, birthdate=1965-12-18T11:10:09)
31
Customer(id=12, firstName=Peter, lastName=Dixon, birthdate=1996-05-09T19:09:23)
32
2019-12-11 23:17:03.453  INFO 6896 --- [           main] o.s.batch.core.step.AbstractStep         : Step: [step1] executed in 153ms
33
2019-12-11 23:17:03.457  INFO 6896 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=job]] completed with the following parameters: [{}] and the following status: [COMPLETED] in 182ms
34
2019-12-11 23:17:03.461  INFO 6896 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
35
2019-12-11 23:17:03.463  INFO 6896 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.


Further Reading

Spring Batch Read an XML File and Write to Oracle Database

Using XML in Java

Topics:
database ,read from xml ,spring ,spring batch ,spring batch tutorial ,xml

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}