• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to create XML file in Java

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 2308
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can use xstream API for this.
 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic