JAX-RS - Returning XML Response

[Last Updated: Aug 29, 2018]
XML is a common media format that RESTful services consume and produce. To deserialize and serialize XML, you can represent requests and responses by JAXB annotated objects. Your JAX-RS application can use the JAXB objects to manipulate XML data. JAXB objects can be used as request entity parameters and response entities. The JAX-RS runtime environment includes standard MessageBodyReader and MessageBodyWriter provider interfaces for reading and writing JAXB objects as entities.

To return XML response from our JAX-RS application we have to go through following least necessary steps.

  1. Create a simple Java Class to be used as XML response.
    1. Annotate the class with @XmlRootElement.
    2. The class must have a no argument public constructor.
    3. We have to provide all getters and setters as by default JAXB uses them for object to XML transformation. If we want fields to be used for transformation, we have to annotate our class with @XmlAccessorType(XmlAccessType.FIELD) as well.

    Here's our class with minimum requirement:
    public class Customer {
        private String id;
        private String name;
        private String address;
        private String phoneNumber;
        public Customer() {
        public Customer(String id) {
   = id;
          //getters and setters

  2. Provide @Produces annotation on our service method to declare the media-type as "application/xml":
    public List<Customer> getCustomers() {

That's it, we don't have to add any additional maven dependency to use JAXB marshalling/unmarshalling.

Example Project

Dependencies and Technologies Used:

  • jersey-core-server 2.22.1: Jersey core server implementation.
  • jersey-container-servlet 2.22.1: Jersey core Servlet 3.x implementation.
  • jersey-test-framework-provider-jdk-http 2.22.1: Jersey Test Framework - JDK HTTP container.
  • DataFactory 0.8: Library to generate data for testing.
  • JDK 1.8
  • Maven 3.0.4

Rest Xml Response Select All Download
  • jaxrs-returning-xml
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • api
        • test
          • java
            • com
              • logicbig
                • example

    To test the application either run the JUnit test CustomerRestServiceTest or run the embedded tomcat server: jaxrs-returning-xml>mvn clean install tomcat7:run-war and then use the following resource link in your browser.



    See Also