In this code snippet you can learn how to convert or unmarshall an XML file into it corresponding POJO. The steps on unmarshalling XML to object begin by creating an instance of JAXBContext
. With the context
object we can then create an instance of Unmarshaller
class. Using the unmarshall()
method and pass an XML file will give us the target POJO as the result.
Let’s see the code snippet below:
package org.kodejava.xml;
import org.kodejava.xml.support.Track;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.net.URL;
import java.util.Objects;
public class JAXBXmlToObject {
public static void main(String[] args) {
try {
URL resource = JAXBXmlToObject.class.getResource("/Track.xml");
File file = new File(Objects.requireNonNull(resource).toURI());
JAXBContext context = JAXBContext.newInstance(Track.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Track track = (Track) unmarshaller.unmarshal(file);
System.out.println("Track = " + track);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here is the context of Track.xml
:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<track id="2">
<title>She Loves You</title>
</track>
package org.kodejava.xml.support;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Track {
private Integer id;
private String title;
public Track() {
}
public Integer getId() {
return id;
}
@XmlAttribute
public void setId(Integer id) {
this.id = id;
}
@XmlElement
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return "Track{" +
"id=" + id +
", title='" + title + '\'' +
'}';
}
}
Maven Dependencies
<dependencies>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-ri</artifactId>
<version>2.3.5</version>
<type>pom</type>
</dependency>
</dependencies>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024