In the following tutorial we will show you how you can convert XML to Object in Java using JAX-B.
First we need to define our model that will be converted to XML representation. Here are a couple of annotations with their explanations what they do.
@XmlRootElement: This annotation defines the root element. It is required by JAX-B, without this, the object cannot be converted into xml.@XmlAccessorType: This tells JAX-B witch access level is used. NONE: Indicates that JAX-B will not convert any properties.FIELD: Indicates that JAX-B will search for annotations on field level.PROPERTY: Indicates that JAX-B will search for annotations on property level.PUBLIC_MEMBER (default): Indicates that JAX-B will search for public members.@XmlAttribute: This tels JAX-B to convert the property or field into an XML attribute.@XmlElement: This tells JAX-B to convert the property or field into an XML element. This is not required. By default JAX-B uses every public non-transient member into an element if the class is annotated with @XmlRootElement.Here is how to convert xml to object in Java.
package com.sheting.basic.xml.jaxb; import java.io.StringReader; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; public class ConvertXmlToObject { public static void main(String... args) throws JAXBException { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + "<Course id=\"1\">\n" + " <name>JAX-B</name>\n" + " <description>Learning Java Architecture for XML Binding(JAX-B)</description>\n" + "</Course>"; // create jaxb context JAXBContext jaxbContext = JAXBContext.newInstance(Course.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Course course = (Course) unmarshaller.unmarshal(new StringReader(xml)); System.out.println(course); } }