How to convert Java Object into/from XML – with Castor & Spring Boot

In the tutorial How to convert Java Object into/from XML, JavaSampleApproach will introduce way to Marshalling & Unmarshalling by an open source XML binding framework Castor with SpringBoot project.

Related Posts:
1. Gson to convert Java Object to/from Json
2. Jackson to convert Java Object to/from Json String


I. Technologies for convert Java Object into/from XML tutorial

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Castor

II. Overview
1. Project Structure

Java Object into from XML project structure

2. Step to do

– Create SpringBoot project
– Create simple Model
– Create XML Converter
– Configure CastorMarshaller & XmlConverter
– Create Mapping file
– Develop main class for checking Marshalling & Unmarshalling
– Run & Check Results

III. Practices
1. Create SpringBoot project

– Open Spring Tool Suite, on main menu, choose File->New->Spring Starter Project, add project info. Press Next, then Finish, a Spring Boot project will be created successfully.

Open pom.xml file, add needed dependencies: Spring Oxm, Castor & xerces

2. Create simple Model

– Create Customer model:

3. Create XML Converter

Create XML Converter for handling Marshaller and Unmarshaller

4. Configure CastorMarshaller & XmlConverter

Because CastorMarshaller implements both Marshaller & Unmarshaller, so CastorMarshaller bean can use for XMLConverter as Marshaller & Unmarshaller:
– public class CastorMarshaller extends AbstractMarshaller
– public abstract class AbstractMarshaller implements Marshaller, Unmarshaller

Details code:

5. Create Mapping file

Mapping file is a way to control what field is element or attribute.

For locating the mapping file, use setMappingLocation method: castorMarshaller.setMappingLocation(appContext.getResource(“classpath:mapping.xml”));

6. Develop main class for checking Marshalling & Unmarshalling

In main class of SpringBoot:

7. Run & Check Results

Run the project with Spring Boot App mode.
Results:
1. Logs:

2. Content of customer.xml:

IV. Sourcecode

SpringBootMarshalling


Related Posts


2 thoughts on “How to convert Java Object into/from XML – with Castor & Spring Boot”

    1. Hi,

      With Castor, We need a Mapping File to control the marshaling behavior. Up to now, We don’t see any support from annotations.

      Regards,

Got Something To Say:

Your email address will not be published. Required fields are marked *

*