This week's book giveaway is in the Agile forum.
We're giving away four copies of Head First Agile and have Andrew Stellman & Jennifer Greene on-line!
See this thread for details.
Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

convert java object using jaxb to xml and vice versa (marshal and unmarshal)  RSS feed

 
Alex Balcha
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am suppose to have a method called save() which should marshall the list of computer parts in the right panel to an XML file. (Check attachment) In reverse, another method called load() that should unmarshall the saved XML file back into an object. So basically, the “Save” event will call save() method and save the list of parts in the right panel to an XML file. The “Load” event should clear the right panel, and call load() method. When load() is called, it should display the unmarshalled data in the right panel. I got "Exit" to work.

I'm having hard time figuring out the "Load" and "Save" parts though. Please help. Thanks.

Screenshot-from-2014-11-07-03-55-12.png
[Thumbnail for Screenshot-from-2014-11-07-03-55-12.png]
 
Gamini Sirisena
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is an approach that you can try..

create an xml schema to represent your computer parts

use jaxb compiler, xjc to generate jaxb annotated java bindings for this schema (java classes)

when you want to save have the toplevel java class populated with values and marshall it using jaxb.
To do this..
create a javax.xml.bind.JAXBContext.
and do
jaxbContext.createMarshaller()
and call .marshall() on the marshaller obtained.
to the .marshall() method you pass a JAXBElement<SomeClassGeneratedByJaxB>
and SomeClassGeneratedByJaxB will be an ojbect already populated by your program through the GUI

when you want to load use a persisted xml file and unmarshal it using jaxb
Like this..
you do a .createUnmarhaller()
and call .unmarshall()
to the .unmarshall() you pass your xml file in some form (look up the api)
cast result from calling .unmarshall() to a JAXBElement<SomeClassGeneratedByJaxB>
then call jaxbElement.getValue() to get your SomeClassGeneratedByJaxB
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!