Java DOM Parser – Modify XML Document

Java DOM Parser – Modify XML Document

Demo Example

Here is the input xml file we need to modify:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
   <supercars company="Ferrari">
      <carname type="formula one">Ferrari 101</carname>
      <carname type="sports">Ferrari 202</carname>
   <luxurycars company="Benteley">
      <carname>Benteley 1</carname>
      <carname>Benteley 2</carname>
      <carname>Benteley 3</carname>

Demo Example:

package com.tutorialspoint.xml;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ModifyXmlFileDemo {

public static void main(String argv[]) {

   try {
      File inputFile = new File("input.xml"); 	    	
      DocumentBuilderFactory docFactory =
      DocumentBuilder docBuilder = 
      Document doc = docBuilder.parse(inputFile);
      Node cars = doc.getFirstChild();
      Node supercar = doc.getElementsByTagName("supercars").item(0);
      // update supercar attribute
      NamedNodeMap attr = supercar.getAttributes();
      Node nodeAttr = attr.getNamedItem("company");

      // loop the supercar child node
      NodeList list = supercar.getChildNodes();
      for (int temp = 0; temp < list.getLength(); temp++) {
         Node node = list.item(temp);
         if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) node;
            if ("carname".equals(eElement.getNodeName())){
               if("Ferrari 101".equals(eElement.getTextContent())){
                  eElement.setTextContent("Lamborigini 001");
            if("Ferrari 202".equals(eElement.getTextContent()))
               eElement.setTextContent("Lamborigini 002");
      NodeList childNodes = cars.getChildNodes();
      for(int count = 0; count < childNodes.getLength(); count++){
         Node node = childNodes.item(count);
         // write the content on console
         TransformerFactory transformerFactory = 
         Transformer transformer = transformerFactory.newTransformer();
         DOMSource source = new DOMSource(doc);
         System.out.println("-----------Modified File-----------");
         StreamResult consoleResult = new StreamResult(System.out);
         transformer.transform(source, consoleResult);
      } catch (Exception e) {

This would produce the following result:

-----------Modified File-----------
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<supercars company="Lamborigini">
<carname type="formula one">Lamborigini 001</carname>
<carname type="sports">Lamborigini 002</carname>

Was this article helpful?

Related Articles

Leave A Comment?

You must be logged in to post a comment.