Friday, September 7, 2012

Write XML in JAVA

XmlWriter.java is a simple XML file generator.

[sourcecode language="java"]
package mysamples;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
*
* @author dinuka
*/
public class XmlWriter {

public static void main(String argv[]) {

try {

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("employees");
doc.appendChild(rootElement);

// staff elements
Element staff = doc.createElement("employee");
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("Dinuka"));
staff.appendChild(firstname);

// lastname elements
Element lastname = doc.createElement("lastname");
lastname.appendChild(doc.createTextNode("Malalanayake"));
staff.appendChild(lastname);

// nickname elements
Element age = doc.createElement("age");
age.appendChild(doc.createTextNode("25"));
staff.appendChild(age);

// salary elements
Element email = doc.createElement("email");
email.appendChild(doc.createTextNode("dinuka.malalanayake@gmail.com"));
staff.appendChild(email);

// 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("Employee.xml"));

// Output to console for testing
//StreamResult result = new StreamResult(System.out);

transformer.transform(source, result);

System.out.println("File saved!");

} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
}
[/sourcecode]

Bettor to read following posts as well

http://malalanayake.wordpress.com/2012/09/07/read-xml-file-to-object-in-java/

http://malalanayake.wordpress.com/2012/09/07/persist-java-object-to-xml/

1 comment: