create and xml file

Hi,

I am sorry to use this as a shortcut instead of "doing the work myself", but there is so much info on the web so I do not know where to start. I just want to perform a simple task.

I have a java object ...

publicclass MySampleObject{

private String name;

private String address;

privateint 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 straightforard way by putting strings into a stringbuffer and writing it to a file.

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

/Helena

[1068 byte] By [HelenaStarMountaina] at [2007-11-27 5:13:43]
# 1

straightforard way by putting strings into a stringbuffer and writing it to a file.

No you should not do it that way

I can give you an example program to create an xml with a little bit search you can finish your home work

package xml;

import org.w3c.dom.*;

import javax.xml.parsers.*;

import javax.xml.transform.*;

import java.io.*;

import javax.xml.transform.stream .*;

import javax.xml.transform.dom.*;

public class createXML{

public Document createDocument(){

try {

DocumentBuilder builder =DocumentBuilderFactory.newInstance().newDocumentBuilder();

Document doc = builder.newDocument();

return doc;

} catch (ParserConfigurationException e) {

e.printStackTrace();

}

return null;

}

public void writeXML(Document doc,String fileName){

try{

File xmlFile = new File(fileName+".xml");

Source source = new DOMSource(doc);

Result result = new StreamResult(xmlFile);

Transformer xformer = TransformerFactory.newInstance().newTransformer();

xformer.transform(source, result);

}catch(Exception e){

e.printStackTrace();

}

}

public static void main(String args[]){

createXML cx = new createXML();

Document xmlDoc = cx.createDocument();

Element element = xmlDoc.createElement("root");

xmlDoc.appendChild(element);

element.appendChild(xmlDoc.createTextNode("TEST"));

cx.writeXML(xmlDoc,"output");

}

}

arunmp25a at 2007-7-12 10:35:24 > top of Java-index,Enterprise & Remote Computing,Enterprise Technologies...
# 2
Thank you very much. I just found another thread that dealt with theis case, and yes your way seem to be the way to do it. I knew there must be a correct way. Excellent!!!/Helena
HelenaStarMountaina at 2007-7-12 10:35:24 > top of Java-index,Enterprise & Remote Computing,Enterprise Technologies...