Switch to full style
JAXB code examples
Post a reply

Unmarshall From XML using JAXB

Wed Jul 08, 2009 12:23 am

Unmarshall From XML using JAXB :

This is example unmarshall the content of Student xml into the java objects .
java code
import jaxbclasses.studentType;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class UnmarshallingTest {

    public static void main (String [] args) {
        try {
            JAXBContext jc = JAXBContext.newInstance ("jaxbclasses");

            Unmarshaller u = jc.createUnmarshaller ();

           File f = new File ("student.xml");
           JAXBElement element = (JAXBElement) u.unmarshal (f);

           studentType student= (studentType) element.getValue ();
           System.out.println ("Student Gender is  : " + student.getGender ());
           System.out.println ("Student Name is : " + item.getName ());
           System.out.println ("Student Age is : " + item.getAge ());
       } catch (JAXBException e) {
           e.printStackTrace ();
       }
   }
}
 


Here is the schema ( XSD file ) .
xml code
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="student" type="studentType"/>
    <xsd:complexType name="studentType">
        <xsd:sequence>
            <xsd:element name="gender" type="xsd:string"/>
            <xsd:element name="name" type="xsd:string"/>
            <xsd:element name="age" type="xsd:integer"/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:schema> 




Re: Unmarshall From XML using JAXB

Wed Jan 26, 2011 12:43 pm

I think there is a small typo in your example,

I think the code should read,
java code
System.out.println ("Student Name is : " + student.getName ());
System.out.println ("Student Age is : " + student.getAge ());


Also it might be worth mentioning that you need to generate the java class from the XSD file you've mentioned. I used the utility plug-in for Eclipse called XJC. Then the code in your example will find the java class for StudentType. Might be obvious for experienced programmers but not for people new to Jaxb.

Good example though, thanks.

Post a reply
  Related Posts  to : Unmarshall From XML using JAXB
 XML using JAXB API in java     -  
 how to use enum in jaxb unmarshalling     -  
 update an xml file with jaxb     -  
 insert a namespace in a tag with jaxb     -  
 update an xml file with jaxb and accessing to its elements     -  
 adding an xmlns attribute xith jaxb     -  
 problem with binding a choice model with jaxb     -  

Topic Tags

Java JAXB, Java XML