java

How to update node value in XML using Java DOM

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

In the followng example, we are going to see how to update the value “25” of the node “age” to “30” by using the setTextContent() 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);
	    	       // Get age element and modify its value
		       if ("age".equals(node.getNodeName())) {
			        node.setTextContent("30");
		       }
		   }

		   // 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
      30
      
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 *