Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to get XML from javaobject using JAXB

krishna chitturi
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have java object and i need to get xml from it, we are using JAXB for unmarshal(java object to xml).we are generating JAXB object it has two methods named marshal and unmarshal.unmarshal is used to get java object from XML , how to call marshal to get xml from jaxb.that unmarshal method is taking Marshallaer as parameter, how can i pass Marshaller as Marshaller is private final class.
please help me out.
PMP Kannan
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello Krishna,
first u should have a DTD for the XML document
let's assume that u have a xml file named Item.xml which has some elements and a DTD file named Item.dtd.
then u should ceate the XML binding schema for the xml doc.
<xml-java-binding-schema version="1.0ea">
<element name="item" type="class" root="true" />
save this as filename.xjs
in the above file the element name is item which is the root element.
then generate java files using the schema compiler.
before all this u should set the classpath pointing to ur jaxb jar file.
now compile to generate java files.
suppose the DTD name is Item.dtd and schema name is Item.xjs, then the compilation will be
java "Item.dtd" "Item.xjs"
after this java files are generated.
u will get a java file named which has methods to manipulate the xml data
u can Unmarshall it like this(from XML to JAVA)

Item item = new Item();
File sItem = null;
try {
sItem= new File("Item.xml");
fileInputStream = new FileInputStream(sItem);
item = item.unmarshal(fileInputStream);
catch(Exception e){}
// do the next step to see the xml file printed in the console
System.out.println(item.toString());// will print the xml Doc as a string

u can marshall it back like this(from JAVA to XML)

Item item = new Item();
FileOutputStream fileOutputStream = null;
File changedItem = new File("NewItem.xml");
fileOutputStream = new FileOutputStream(changedItem);
} catch (IOException e){
} finally {

check the file written in the directory. it will be a xml file
that's it
In the country of the blind, one eye'd man is the king
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic