Hi All,
Here I try to write a simple XML file using java code.
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 xmlWrite {
public static void main(String argv[]) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// create root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Department");
doc.appendChild(rootElement);
// create a employee elements
Element Empl = doc.createElement("Employee");
rootElement.appendChild(Empl);
// set attribute to employee element
Attr attr = doc.createAttribute("id");
attr.setValue("1");
Empl.setAttributeNode(attr);
// firstname elements of employee
Element fname = doc.createElement("FirtName");
fname.appendChild(doc.createTextNode("Skitech"));
Empl.appendChild(fname);
// lastname elements of employee
Element lname = doc.createElement("LastName");
lname.appendChild(doc.createTextNode("krish"));
Empl.appendChild(lname);
// nickname elements of employee
Element pname = doc.createElement("NickName");
pname.appendChild(doc.createTextNode("bala"));
Empl.appendChild(pname);
// salary elements of employee
Element sal = doc.createElement("salary");
sal.appendChild(doc.createTextNode("200000"));
Empl.appendChild(sal);
// write above details in XML File
TransformerFactory tF = TransformerFactory.newInstance();
Transformer trans = tF.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:\\file.xml"));
// Output write to console for your reference
result = new StreamResult(System.out);
trans.transform(source, result);
System.out.println("Your file saved! in the C:\\file.xml location :-)");
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (TransformerException t) {
t.printStackTrace();
}
}
}
Output :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Department>
<Employee id="1">
<FirtName>Skitech</FirtName>
<LastName>krish</LastName>
<NickName>bala</NickName>
<salary>200000</salary>
</Employee>
</Department>
No comments:
Post a Comment