java

How to add child node in XML using Java DOM

In this tutorial, we are going to see how to add child node in XML using Java DOM Parser. To add child node in XML we can use the appendChild() method as shown in the following example.

We will work on the following XML file (test.xml):

<?xml version="1.0" encoding="UTF-8" standalone="no" ?> 

   
      Alex
      25
      
San Francisco
 

Program to add child node in XML using Java DOM:

In the followng example, we are going to see how to add a new element “job” to the parent node which is “employee”.

import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;

public class Main {

	public static void main(String argv[]) {

	   try {
		   String file = "c:\\test.xml";
		   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		   DocumentBuilder db = dbf.newDocumentBuilder();
		   Document doc = db.parse(file);

		   // Get the parent node
		   Node entreprise = doc.getFirstChild();

		   // Get the employee element
		   Node employee = doc.getElementsByTagName("employee").item(0);

		   // Add a new node
		   Element job = doc.createElement("job");
		   job.appendChild(doc.createTextNode("Commercial"));
		   employee.appendChild(job);

		   // write the content to the xml file
		   TransformerFactory tf = TransformerFactory.newInstance();
		   Transformer transformer = tf.newTransformer();
		   DOMSource src = new DOMSource(doc);
		   StreamResult res = new StreamResult(new File(file));
		   transformer.transform(src, res);

	   } catch (Exception e) {
			e.printStackTrace();
	   }
	}
}

Result:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?> 

   
      Alex
      25
      
San Francisco
Commercial
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *