Managing XML with Spring Boot Controllers

This article will discuss how to consume and produce XML files using Spring Boot REST Controllers. We will also show in simple steps how to serialize Java objects that we will use as body of our Request and Response.

Adding Project dependencies

Firstly, we need to add a dependency we will use to serialize and deserialize the XML Content. For this purpose, we can add the jackson-dataformat-xml dependency to our Spring Boot starters:

<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

Coding the Model

Next step, will be coding a minimal Java Bean class that we will accept as XML parameter and return as Response as well. Add the Customer Class to your project:

@JacksonXmlRootElement
public class Customer {
    public Customer() {
    } 
    public Customer(String firstName, String lastName ) {
		this.firstName = firstName;
		this.lastName = lastName;
    }
    String firstName;
    String lastName;
    // Getters/Setters omitted for brevity
}

Notice we are using the com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement annotation. This annotation allows to specify the root element name for an XML document when serializing a Java object to XML using Jackson. It is used in conjunction with other Jackson annotations such as @JsonProperty and @JacksonXmlProperty.

Coding the REST Controller

Finally, we will add the REST Controller with an endpoint which consumes and produces XML Content:

@RestController
public class MyController {

    @RequestMapping(path = "/xml", 
    method = RequestMethod.POST, produces = MediaType.APPLICATION_XML_VALUE,
    consumes = MediaType.APPLICATION_XML_VALUE)
 
    public ResponseEntity<Customer> xml(@RequestBody Customer c) {       
        System.out.println("Received "+c);
        c.setLastName("changed");
        return new ResponseEntity<>(c, HttpStatus.OK);
    }
}

Key points here:

We are using the @RequestBody annotation in the method of our Spring controllers. This annotation indicates that Spring should deserialize a request body into an object. This object is passed as a handler method parameter.

Also, our endpoint produces and consumes data as XML.

Finally, we are using ResponseEntity to manipulate the Response and set a field of the Customer class with some different values.

Let’s test it. From Postman or any tool, send an XML Payload:

spring boot xml rest controller

As you can see, the REST Controller perform the following actions:

When it receives an XML in the RequestBody, it serializes the content into the Customer Class, as you can see from the log message:

Received Customer [firstName=John, lastName=Doe]

Then, by using the ResponseEntity Class it returns a modified XML text as Response.

Conclusion

This article was a quick walkthrough a simple Spring Boot application which consumes and produces XML Content via the Jackson library