aspose file tools*
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 EJB 3 in Action this week in the EJB and other Java EE Technologies 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
Author

How to create XML file in Java

Kalyani Nemala
Greenhorn

Joined: Nov 30, 2006
Posts: 9
Hi,

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:


<persons>
<person>
<name>Helena</name>
<address>Sweden</address>
<phonenumber>01234567</phonenumber>
</person>
</persons>



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.

Thanks,
Kalyani
Rahul Bhattacharjee
Ranch Hand

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


Rahul Bhattacharjee
LinkedIn - Blog
The Dunce Baron
Greenhorn

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 org.w3c.dom.ls packages. Though I've never used the org.w3c.dom.ls.LSSerializer 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
Marshal

Joined: Mar 22, 2005
Posts: 39530
    
  27
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.


Ping & DNS - updated with new look and Ping home screen widget
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to create XML file in Java
 
Similar Threads
annotations on entity class with spring oxm and jaxb for ArrayList
XML Node Parsing Problem , when Node owns NodeList using Xercer , HELP !!!!
How to Convert automaticaly from XML to Java Object and Vice versa ?
return type
Process multiple node occurences using JAXB