java

How to remove XML Node using Java DOM Parser

In this tutorial, we are going to see how to remove XML Node using Java DOM Parser. To remove a node in XML we can use the removeChild() 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 remove XML Node using Java DOM Parser:

In the followng example, we are going to see how to remove the node “name” by using the removeChild() method.

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);

		   // Get the list of child nodes of employee
		   NodeList list = employee.getChildNodes();

		   for (int i = 0; i < list.getLength(); i++) {
		       Node node = list.item(i);
		       //Remove "name" node
		       if ("name".equals(node.getNodeName())) {
		           employee.removeChild(node);
		       }
		   }

		   // 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" ?> 

   
      25
      
San Francisco
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 *