Search code examples
javaxmlxsdjaxb2

Java: Populating .xsd-generated class from .xml file


I have a class that was generated from an .xsd file, and I have an .xml file that contains data that adheres to the schema in the .xsd. Something like:

  • XML schema file: MyObject.xsd
  • Java class generated from schema: MyObject.java
  • XML that matches the schema: MyObject.xml

Is there an easy way for me to deserialize MyObject.xml into an instance of MyObject.java? I'm hoping for something easier than hand-walking through the DOM elements and setting all the properties on the object.

Basically, I'm looking for the functionality in java.beans.XMLDecoder, but since my .xml file was not created from the XMLEncoder, I do not believe that I can use the decoder.


Solution

  • First you need to create a JAXBContext instance using the static newInstance method. Then create an Unmarshaller instance using the createMarshaller method and call the appropriate unmarshal method on that instance:

    InputStream is = new FileInputStream("MyObject.xml");
    JAXBContext jc = JAXBContext.newInstance(MyObject.class);
    Unmarshaller u = jc.createUnmarshaller();
    MyObject o = (MyObject)u.unmarshal(is);