x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    Modify XML file in java using DOM parser

    You can modify the contents of a XML file using DOM Parser. You can modify, remove, add elements, attributes of XML file using DOM Parser.

    XML file that you want to modify: employees.xml
    <?xml version = "1.0"?>    
    <employees>
        <employee id="123">
            <firstname>Mohit</firstname>
            <lastname>Bisht</lastname>
    	</employee>
        <employee id="456">
            <firstname>Samit</firstname>
            <lastname>Ahlawat</lastname>
        </employee>
    </employees>
    	

    1) Add new element in XML file with nodes and text value & update an existing element

    Below example shows how to add new element with id = "345" & update firstname of element with id="123"

    // Modifies XML file    
    import java.io.File;
    
    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 javax.xml.transform.stream.StreamResult;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    				
    public class ModifyXMLDOMParser {
        public static void main(String[] args) {
            try {
                File inputFile = new File("E:\\employees.xml");
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(inputFile);
                doc.getDocumentElement().normalize();
                    
                // update firstname of element with id="123"
                NodeList employees = doc.getElementsByTagName("employee");
                for(int i=0; i<employees.getLength();i++){
                    Element emp = (Element) employees.item(i);
                    Node name = emp.getFirstChild();
                    if ("Mohit".equalsIgnoreCase(name.getNodeValue())) {
                        name.setNodeValue("Mickey");
                    }
                }
                    
                // add new element with id = "345".
                Element employee = doc.createElement("employee");
                employee.setAttribute("id", "345");
                Element node1 = doc.createElement("firstname");
                node1.appendChild(doc.createTextNode("William"));
                employee.appendChild(node1);
                Element node2 = doc.createElement("lastname");
                node2.appendChild(doc.createTextNode("Wallace"));
                employee.appendChild(node2);
                    
                Element emp = (Element) employees.item(0);
                emp.appendChild(employee);
                    
                // write the content into xml file
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                DOMSource source = new DOMSource(doc);
                StreamResult result = new StreamResult(new File("E:\\employees.xml"));
                transformer.transform(source, result);
                    
            } catch (Exception e) {
                e.printStackTrace();
            } 
        }
          
    }
    	

    Generated XML :

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <employees>
        <employee id="123">
            <firstname>Mohit</firstname>
            <lastname>Bisht</lastname>
    	</employee>
        <employee id="456">
            <firstname>Samit</firstname>
            <lastname>Ahlawat</lastname>
        </employee>
        <employee id="345">
            <firstname>William</firstname>
            <lastname>Wallace</lastname>
        </employee>
    </employees>
        

    2) Delete an element in XML file & update atribute value in an existing element

    Below example shows how to delete an element with attribute id = "123" & update atribute value of element with id="456" to id="789"

    // Modifies XML file    
    import java.io.File;
    
    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 javax.xml.transform.stream.StreamResult;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    				
    public class ModifyXMLDOMParser {
        public static void main(String[] args) {
            try {
                File inputFile = new File("E:\\employees.xml");
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(inputFile);
                doc.getDocumentElement().normalize();
                    
                NodeList nodeList = doc.getElementsByTagName("employee");
                int index = 0;
                
                for (int i = 0; i < nodeList.getLength(); i++) {
                    Node node = nodeList.item(i);
                    
                    if (node.getNodeType() == Node.ELEMENT_NODE) {
                        NamedNodeMap nodeMap = node.getAttributes();
                    
                        for (int j = 0; j < nodeMap.getLength(); j++) {
                            Node node2 = nodeMap.item(j);
                            if (node2.getNodeName().equalsIgnoreCase("id")) { 
                                if (node2.getNodeValue().equalsIgnoreCase("123")) {
                                	index = i; // get the index of node ned to be removed
                                }
                                if (node2.getNodeValue().equalsIgnoreCase("456")) {
                                	node2.setNodeValue("789"); // update atribute value
                                }
                            }
                        }
                    }
                }
                
                // remove element    
                Node node = nodeList.item(index);
                doc.getElementsByTagName("employees").item(0).
                    removeChild(node);;
                                
                // write the content into xml file
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                DOMSource source = new DOMSource(doc);
                StreamResult result = new StreamResult(new File("E:\\employees.xml"));
                transformer.transform(source, result);
                    
            } catch (Exception e) {
                e.printStackTrace();
            } 
        }
          
    }
    	

    Generated XML :

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <employees>
        <employee id="789">
            <firstname>Samit</firstname>
            <lastname>Ahlawat</lastname>
        </employee>
    </employees>
        

    References:

    https://docs.oracle.com/javase/tutorial/jaxp/xslt/writingDom.html

    Parse XML using DOM