How to add new node in XML file using DOM Parser in Java?



Problem Description:


Suppose we have following XML file as an example.

<Employees>
   <Employee id="1">
       <name>abc</name>
       <age>23</age>
   </Employee >
  <Employee id="2">
       <name>xyz</name>
       <age>29</age>
   </Employee>
   <Employee id="3">
       <name>lmn</name>
       <age>34</age>
   </Employee>
</Employees>

Here requirement is to add new child node Employee. User has to enter all the relevant information related to Employee.


Steps:


1) Parse XML file or Create an instance of Document interface present in org.w3c.dom.* package.

For Creating an instance of Document interface we need to use DocumentBuilderFactoryDocumentBuilder classes present in javax.xml.parsers.* package and File class present in java.io.* package.

File file = new File(XML_file_location);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(file);

2) Enter all relevant information related to Employee.


Add new node in XML file using DOM Parser
Figure 1

3) Now create new node (Employee) as follows.

  • Create an instance of Element interface present in org.w3c.dom.* package. 
          Element child= document.createElement("Employee");
  • For uniquely identifying this node we need to set its id. With the help of NodeList interface we can do this task as follows.
          NodeList list=document.getElementsByTagName("Employee");
          int count=list.getLength();
          element.setAttribute("id", String.valueOf(++count));
  • Employee has some properties, for each property we need to create element as below.
           Element property = document.createElement(propertyName);
  • We can set its value as below.
           property.setTextContent(value);
  • One by one make these properties as a child element of Employee element as below.
           child.appendChild(property);


4) Now make this new node (Employee) as a child node of root (Employees) node.

document.getDocumentElement().appendChild(element);

5) Create an instance of Transformer class present in javax.xml.transform.* package. 

For creating an instance of Transformer class we need to use TransformerFactory class present in javax.xml.transform.* package.

TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();


6) Set xml file indentation (Optional)


transformer.setOutputProperty(OutputKeys.INDENT, "yes");

7) Create an instance of DOMSource class present in javax.xml.transform.dom.* package and pass instance of Document interface created in step 1.


DOMSource source = new DOMSource(document);

8) Create an instance of StreamResult class present in javax.xml.transform.stream.* package.


For creating an instance of StreamResult class first we need to create an instance of File class present in java.io.* package.

File file = new File(location_of_xml_file);
StreamResult result = new StreamResult(file);


9) Transform XML Source to a Result.


transformer.transform(source, result);


Software Required:

  1. JDK
  2. Eclipse
  3. Maven
Note : I suggest to use latest version of all the software. If you need any help regarding these software installation please comment below I will help you.

Project Structure:


Java XML DOM Parser structure part 4
Figure 2

Java Code:


pom.xml


Employee.java


AddEmployee.java


Output:


Java XML DOM Parser output part 4
Figure 3

employee.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Employees>
<Employee id="1">
<name>Rohit</name>
<gender>male</gender>
<age>25</age>
<role>Programmer</role>
</Employee>
<Employee id="2">
<name>Bhavna</name>
<gender>female</gender>
<age>20</age>
<role>Student</role>
</Employee>
<Employee id="3">
<name>Shubham</name>
<gender>male</gender>
<age>24</age>
<role>Singer</role>
</Employee>
</Employees>


Download Project


Click here for more questions on DOM Parser.

References:


https://docs.oracle.com/javase/7/docs/api/javax/xml/parsers/DocumentBuilderFactory.html
https://docs.oracle.com/javase/7/docs/api/javax/xml/parsers/DocumentBuilder.html


Thank you friends, I hope you have clearly understood the solution of this problem. If you have any doubt, suggestion or query please feel free to comment below. You can also discuss this solution in our forum.

About Author:

I am simple guy with lot of ambitions. My main motive is to share whatever knowledge I have related to programming. With me you can easily learn how to solve any programming problem in Java.You can connect with me on social networking sites also.


Let's Get Connected: Linkedin | Facebook |

How to add new node in XML file using DOM Parser in Java? How to add new node in XML file using DOM Parser in Java? Reviewed by Unknown on 10/06/2017 Rating: 5

No comments:

Please provide your valuable comments. If you have any suggestion please share with me I will work on it and if you have any question or doubt please ask, don't hesitate. I am your friend, i will clarify all your doubts.

Powered by Blogger.