java

How to change an attribute value in XML using Java DOM

In this tutorial, we are going to see how to change an attribute value in XML using Java DOM Parser. To change an attribute 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 change an attribute value in XML using Java DOM:

In the followng example, we are going to see how to change the value of the attribute “id” from 1 to 5 of element “employee” 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);

		   // Change attribute employee id = "1" to id = "5"
		   NamedNodeMap attr = employee.getAttributes();
		   Node node = attr.getNamedItem("id");
		   node.setTextContent("5");

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