Create XML file using java Create XML file using java java java

Create XML file using java


You can use a DOM XML parser to create an XML file using Java. A good example can be found on this site:

try {    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();    //root elements    Document doc = docBuilder.newDocument();    Element rootElement = doc.createElement("company");    doc.appendChild(rootElement);    //staff elements    Element staff = doc.createElement("Staff");    rootElement.appendChild(staff);    //set attribute to staff element    Attr attr = doc.createAttribute("id");    attr.setValue("1");    staff.setAttributeNode(attr);    //shorten way    //staff.setAttribute("id", "1");    //firstname elements    Element firstname = doc.createElement("firstname");    firstname.appendChild(doc.createTextNode("yong"));    staff.appendChild(firstname);    //lastname elements    Element lastname = doc.createElement("lastname");    lastname.appendChild(doc.createTextNode("mook kim"));    staff.appendChild(lastname);    //nickname elements    Element nickname = doc.createElement("nickname");    nickname.appendChild(doc.createTextNode("mkyong"));    staff.appendChild(nickname);    //salary elements    Element salary = doc.createElement("salary");    salary.appendChild(doc.createTextNode("100000"));    staff.appendChild(salary);    //write the content into xml file    TransformerFactory transformerFactory =  TransformerFactory.newInstance();    Transformer transformer = transformerFactory.newTransformer();    DOMSource source = new DOMSource(doc);    StreamResult result =  new StreamResult(new File("C:\\testing.xml"));    transformer.transform(source, result);    System.out.println("Done");}catch(ParserConfigurationException pce){    pce.printStackTrace();}catch(TransformerException tfe){    tfe.printStackTrace();}


You can use Xembly, a small open source library that makes this XML creating process much more intuitive:

String xml = new Xembler(  new Directives()    .add("root")    .add("order")    .attr("id", "553")    .set("$140.00")).xml();

Xembly is a wrapper around native Java DOM, and is a very lightweight library.


Have look at dom4j or jdom. Both libraries allow creating a Document and allow printing the document as xml. Both are widly used, pretty easy to use and you'll find a lot of examples and snippets.

dom4j - Quick start guide