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.
package 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();
}
}
}
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();
}
}
}
Comments
Post a Comment