• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to create XML file in Java

 
Kalyani Nemala
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use xstream API for this.
 
The Dunce Baron
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic