Java examples on Java XML
- How do I build object from XML file using SAX?
- How do I parse an XML file using SAX?
- How do I get attributes of element during SAX parsing?
- How do I handle error when parsing an XML file using SAX?
- How do I define the XML element order in JAXB?
- How to convert object to XML using JAXB?
- How to create an XML file of a POJO using JAXB?
- How do I change the XML root element name in JAXB?
- How to convert an XML file into object using JAXB?
- How to map a bean property to an XML attribute in JAXB?
- How to generate a wrapper element around XML representation in JAXB?
How to convert an XML file into object using JAXB?
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.example.jaxb;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
public class JAXBXmlToObject {
public static void main(String[] args) {
try {
File file = new File("Track.xml");
JAXBContext context = JAXBContext.newInstance(Track.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Track track = (Track) unmarshaller.unmarshal(file);
System.out.println("Track = " + track);
} catch (JAXBException 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>