简体   繁体   中英

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM