In previous tutorial, we learned How to Read XML Data in Java ?, Now in this Tutorial I will tell you how you can save your data in the XML File format.
At the end of the Example our following XML file with the name student.xml will created.
<school>
<student rollno="1">
<firstname>NAVEEN</firstname>
<lastname>RAWAT</lastname>
<age>16</age>
</student>
</school>
Following is the Java File with the name XmlWritterDemo.java which are saving the data with the help of DOM Parser
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 XmlWritterDemo {
public static void main(String[] args) {
try{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.newDocument();
Element root = doc.createElement("SCHOOL");
doc.appendChild(root);
Element student = doc.createElement("STUDENT");
root.appendChild(student);
Attr attr = doc.createAttribute("ROLLNO");
attr.setValue("1");
student.setAttributeNode(attr);
Element fname = doc.createElement("FIRSTNAME");
fname.appendChild(doc.createTextNode("NAVEEN"));
student.appendChild(fname);
Element lname = doc.createElement("LASTNAME");
lname.appendChild(doc.createTextNode("RAWAT"));
student.appendChild(lname);
Element age = doc.createElement("AGE");
age.appendChild(doc.createTextNode("16"));
student.appendChild(age);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("student.xml"));
transformer.transform(source, result);
System.out.println("File Successfully Saved");
}catch(ParserConfigurationException pce){
pce.printStackTrace();
}catch(TransformerException te){
te.printStackTrace();
}
}
}