Simple way to Write to XML using Java
Jul 30th, 2009 | By admin | Category: JavaOften it becomes necessary for application programmer to read from or write to XML pragmatically. There are many different ways to deal with XML using Java programming language. I am going to share one of them. Let me start this post with an use case. While reading through the use case , we should learn how to use Java to write to XML file.
Use case :
Look at the following XML file (dept_HR_Products.xml) which holds the information about different products in a department and several employees belongs to each product. The XML defines , the department dept_HR_Products has three products , product_1 , product_2 and product_3 respectively. product_1 has 2 employees , product_2 has 1 employee where product_3 has 2 employees. This XML holds the name, designation(desig in the XML), employee Id and Manager name as well.
Spend some time to look and understand the XML file.
Listing 1 : dept_HR_Products.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <dept_HR_Products> <product_1> <employee> <id>2345</id> <desig>Associate</desig> <manager>Alex Braton</manager> <name>Yan Botham</name> </employee> <employee> <id>1000</id> <desig>Product Manager</desig> <manager>Borrek Marteen</manager> <name>Krishna Sharma</name> </employee> </product_1> <product_2> <employee> <id>122</id> <desig>sse</desig> <manager>Alex B</manager> <name>Chand T</name> </employee> </product_2> <product_3> <employee> <id>34</id> <desig>sse</desig> <manager>Vipul T</manager> <name>Rahim</name> </employee> <employee> <id>340</id> <desig>sse</desig> <manager>Vipul T</manager> <name>Sharma</name> </employee> </product_3> </dept_HR_Products>
Lets assume , our application demands us to insert a new employee record to the XML file on click on a button from GUI. So we provide all the details like , employee ID , Designation , Name and Manager’s name from the GUI and click on the submit button to insert the employee record to XML(This is an example , I am sure that you would be having a plan of using a database to do it ). To insert the record to the XML , we need XML node notation . We need to form a node like following and write a routine to insert it ,
<employee> <id>100</id> <desig>Product Manager</desig> <manager>Simon T</manager> <name>Krishna Sharma</name> </employee>
So , we are sure about the attributes an employee can have in our XML store. We should create a DTO(Data transfer object) for Employee which should consist all the attributes an employee can have and setters , getters method for them.
A Employee DTO should look like ,
Listing 2 : Employee DTO
package com.etecguide.java.xmlWrite.dto;
import java.io.Serializable;
public class Employee implements Serializable{
private String userName;
private String empId;
private String designation;
private String manager;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getManager() {
return manager;
}
public void setManager(String manager) {
this.manager = manager;
}
// Overriding toString() method
public String toString(){
StringBuffer sb = new StringBuffer();
sb.append(getUserName());
sb.append(":");
sb.append(getEmpId());
sb.append(":");
sb.append(getDesignation());
sb.append(":");
sb.append(getManager());
sb.append("]");
return sb.toString();
}
}
Now , Lets get into the business. Lets have a look at the Listing 3 which lists the Java code to insert a node to the XML file. Input parameters to the method are ,
xmlFileName – Name of the XML File.
productName – Name of the product(product_1,product_2,product_3) selected from the GUI.
employee – Employee DTO object which would have populated with the employee details provided from GUI.
Have a look at the following code and lets do a step-by-step analysis.
Listing 3 : Write to the XML file
public static void addToDepartment(String xmlFileName, String productName,
Employee employee) throws ParserConfigurationException,
SAXException, IOException, TransformerException {
File file = new File(xmlFileName);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
Element rootElement = doc.getDocumentElement();
NodeList product = rootElement.getElementsByTagName(productName);
for (int i = 0; i < product.getLength(); i++) {
Node productNode = product.item(i);
Node empNode = doc.createElement("employee");
Node idNode = doc.createElement("id");
Node idTextNode = doc.createTextNode("id");
idTextNode.setTextContent(employee.getEmpId());
idNode.appendChild(idTextNode);
Node desigNode = doc.createElement("desig");
Node desigTextNode = doc.createTextNode("desig");
desigTextNode.setTextContent(employee.getDesignation());
desigNode.appendChild(desigTextNode);
Node managerNode = doc.createElement("manager");
Node managerTextNode = doc.createTextNode("manager");
managerTextNode.setTextContent(employee.getManager());
managerNode.appendChild(managerTextNode);
Node nameNode = doc.createElement("name");
Node nameTextNode = doc.createTextNode("name");
nameTextNode.setTextContent(employee.getUserName());
nameNode.appendChild(nameTextNode);
empNode.appendChild(idNode);
empNode.appendChild(desigNode);
empNode.appendChild(managerNode);
empNode.appendChild(nameNode);
productNode.appendChild(empNode);
break;
}
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer trs = tFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new FileOutputStream(new File(
xmlFileName)));
trs.transform(source, result);
}
We create a file object using the file name at the line number 5. Then create a DocumentBuilderFactory and a DocumentBuilder. We need a Document object that represents the parsed xml document. We create a Document object at the line number 8. Next Step is to get the root Element ( i.e, dept_HR_Products) and then get the list of all the nodes inside. As we know the product name , we can form a product node element to get all the child node under the specified product node. We achieve this at the line number 12.
The use of for-loop is unnecessary in this case ( as , we know the product name). We can directly get a product node using ,
Node productNode = product.item(0);
instead of iterating through the for-loop. .With this the new node for employee should be written to the XML file.
Now we are going to create the node for the new employee along with the data we have passed through Employee DTO. Line 19-37 does this. We create an
We create a Transformer object at the line number 49 and create a Dom Source from the document at the line number 51. We create a StreamResult object using the xml file. Finally , the transformation happen at line number 55 ,
trs.transform(source, result);
There could be several other ways to do the same. One should change the above code depending on the structure of the node in the XML. Best of luck for your all future insertion to the XML. Share your views and ideas to do insert to the XML using different techniques.

I have never used the DOM model but use SAX with XSL. This seems a convenient method for different types of output whether the output be native XML, cXML, pdf, csv or other types of input/output when parsing and additing either attributes/elements to an xml document. There are pros and cons to this approach but it depends on the developer. Stylesheets can become more robust in large scale operations and manipulations but consume more processing power on the hardware side.
Everything is always up to the end user on how to manipulate XML files. Good reference though.
couldn’t have done it faster and cleaner using castor (http://www.castor.org/)?
Yes. Castor (www.castor.org) is a free, open source tool that binds object models to, things like XML. Same thing can be achieved easily using Castor. This post is suites the environment when a developer is relying on nothing other than the Java. I appreciate your suggestion of using Castor.
Thanks,
- Admin
Qualunque cosa.
The author of etechguide.in has written an excellent article. You have made your point and there is not much to argue about. It is like the following universal truth that you can not argue with: It’s hard to retro-fit correctness. Thanks for the info.
I am bare impressed with the article I have just read. I wish the writer of etechguide.in can continue to provide so much useful information and unforgettable experience to etechguide.in readers. There is not much to state except the following universal truth: When in doubt, you should probably keep it to yourself. I will be back.
this post is very usefull thx!
Good brief and this mail helped me alot in my college assignement. Gratefulness you for your information.