how to write xml file in jva?

  
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;

public class XmlApp {

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("college");
doc.appendChild(rootElement);

// student element
Element st = doc.createElement("Student");
rootElement.appendChild(st);

// set attribute to st element
Attr attr = doc.createAttribute("stundentId");
attr.setValue("1");
st.setAttributeNode(attr);

// shortest way
// st.setAttribute("studentid", "1");

// studentname element
Element sname = doc.createElement("studentName");
sname.appendChild(doc.createTextNode("sunny"));
st.appendChild(sname);

// address element
Element address = doc.createElement("address");
address.appendChild(doc.createTextNode("hyderabad"));
st.appendChild(address);

// email elements
Element email = doc.createElement("email");
email.appendChild(doc.createTextNode("sunny@gmail.com"));
st.appendChild(email);

// phone number elements
Element phno = doc.createElement("phoneNumber");
phno.appendChild(doc.createTextNode("9080706050"));
st.appendChild(phno);

// write the content into xml file and store the file in some location.
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("E:\\StudentFile.xml"));

transformer.transform(source, result);

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

catch (ParserConfigurationException pce) {
pce.printStackTrace();
catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
}

Output for the above program is:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<college>
<Student stundentId="1">
<studentName>sunny</studentName>
<address>hyderabad</address>
<email>sunny@gmail.com</email>
<phoneNumber>9080706050</phoneNumber>

</Student></college>

Search This Blog

All the rights are reserved to this blog is belongs to me only.. Powered by Blogger.