my dog learned polymorphism
The moose likes XML and Related Technologies and the fly likes How to create XML file in Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "How to create XML file in Java" Watch "How to create XML file in Java" New topic

How to create XML file in Java

Kalyani Nemala

Joined: Nov 30, 2006
Posts: 9

I have a java object ...

public class MySampleObject {

private String name;
private String address;
private int phonenumber;


And I want to put it into an xml file like this:


My plan is to do it the straightforward way by putting strings into a stringbuffer and writing it to a file.

Is there a smarter xml-ish way to do it ?

Please help.

Rahul Bhattacharjee
Ranch Hand

Joined: Nov 29, 2005
Posts: 2308
You can use xstream API for this.

Rahul Bhattacharjee
LinkedIn - Blog
The Dunce Baron

Joined: Apr 19, 2007
Posts: 9
Hi Kalyani,
I'm pretty new to XML myself. But what you are describing sounds like it might be an appropriate application for "DOM" (Document Object Model).

Check out the Java API for the org.w3c.dom and packages. Though I've never used the to output XML, it seems like a good candidate. Besided this, there are lots and lots of other ways to take an in-memory representation of XML data (a DOM) and serialize it to disk.
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
If the class is a Java Bean (i.e., it has getters and setters along with those fields), you can let the java.beans.XMLEncoder/XMLDecoder classes do the work.
I agree. Here's the link:
subject: How to create XML file in Java
jQuery in Action, 3rd edition