After importing Jackson, we can start using its
XmlMapper
class for reading and writing XML.
XmlMapper xmlMapper = new XmlMapper();
//POJO -> XML
String xml = xmlMapper.writeValueAsString(pojo);
//XML -> POJO
Class pojo = xmlMapper.readValue(xml);
XMLMapper
is the most important class for handling XML documents with Jackson. It provides methods to read and write XML to the following sources and targets.
String
Byte[]
java.io.File
java.io.InputStream
and
java.io.OutputStream
java.io.Reader
and
java.io.Writer
//Write to String
String xml = xmlMapper.writeValueAsString(pojo);
//Write to file
xmlMapper.writeValue(new File("data.xml"), pojo);
//Read from String
Pojo pojo = xmlMapper.readValue(xmlString, Pojo.class);
//Read from File
Pojo pojo = xmlMapper.readValue(new File("data.xml"), Pojo.class);
Using its
enable()
and
disable()
methods, we can trun on and off various behaviors specific to XML marshalling and unmarshalling such as:
Let us take an example of
Article
class. We will first check the default XML generated for its instance, and then we will customize the XML by applying annotations to the
Article
class.
class Article {
private Long id;
private String title;
private List<String> tags;
//Constructors, getters, setters and toString method
In the following examples, we use the same code for marshalling.
XmlMapper xmlMapper = new XmlMapper();
Article article = new Article(1L, "Test Title", List.of("Tag1", "Tag2"));
String articleXml = xmlMapper.writeValueAsString(article);
System.out.println(articleXml);
3.1. Default XML without Annotations
The default XML takes the XML tag names from class and member field names, including capitalization.
Use @JacksonXmlRootElement to customize the name of the root element.
@JacksonXmlRootElement(localName = "article")
class Article { ... }
Check out the generated XML putout.
<article>....</article>
3.3. Making XML Attribute
Use @JacksonXmlProperty(isAttribute = true) to mark a field as an XML attribute rather than an XML element.
@JacksonXmlRootElement(localName = "article")
class Article {
@JacksonXmlProperty(isAttribute = true)
private Long id;
Check out the generated XML putout.
<article id="1">...</article>
3.4. Customizing Lists
Use @JacksonXmlElementWrapper to on a List type to create the list wrapper element. The individual elements can be customized using the @JacksonXmlProperty.
This Jackson tutorial taught us to serialize and deserialize the Java Object to XML document with simple and easy examples. We learned to customize and use the XmlMapper class for controlling the specific behavior during the conversion processes.
A fun-loving family man, passionate about computers and problem-solving, with over 15 years of experience in Java and related technologies.
An avid Sci-Fi movie enthusiast and a fan of Christopher Nolan and Quentin Tarantino.