Modify XML with XPath

How to search and replace a tag value in XML file using Java. Read and update XML file in Java

Here we will see How to replace text in XML file using Java.

Using XPath in the below example we are going to see "How to search and replace a tag value in XML file using Java".

Reading XML file in java

We use the below data.xml file

<?xml version="1.0" encoding="ISO-8859-1"?>
<employees>
    <employee>
        <name>Andrew</name>
        <Age>24</Age>
        <Gender>M</Gender>
        <PostalCode>54879</PostalCode>
    </employee>
    <employee>
        <name>Boris</name>
        <Age>28</Age>
        <Gender>M</Gender>
        <PostalCode>78745</PostalCode>
    </employee>
    <employee>
        <name>Charles</name>
        <Age>232</Age>
        <Gender>M</Gender>
        <PostalCode>53454</PostalCode>
    </employee>
</employees>
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(
    new InputSource("data.xml"));

XPATH for searching

//employees/employee/name[text()='Andrew']

The above xpath expression maps to all name attribute. XPath is the full path to the node. The below xml snippet represents the matched xml part from the xpath expresssion.

<employees>
    <employee>
        <name>Andrew</name>
    </employee>
</employees>    
XPath xpath = XPathFactory.newInstance().newXPath();

//Select the current value
NodeList nodes = (NodeList) xpath.evaluate("//employees/employee/name[text()='Andrew']", doc,
    XPathConstants.NODESET);

Replace the node value

Once the NodeList object is available containing the nodes, we need to simply update the text content. The document object loaded now contains the updated xml data.

//replace all nodes matching with new value
for (int idx = 0; idx < nodes.getLength(); idx++) {
  nodes.item(idx).setTextContent("David");
}

Replacing the xml file

In order to search and replace a tag value in XML file, we are going to write the document into a new file. The document object is already loaded into the program and it needs to be written back to a file.

Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(new DOMSource(doc), new StreamResult(new File("data_new.xml")));

If we wish to keep the name unchanged, we must rename/delete the old xml file and rename new file to data.xml

Full Java code

Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(
    new InputSource("data.xml"));

XPath xpath = XPathFactory.newInstance().newXPath();

//Select the current value
NodeList nodes = (NodeList) xpath.evaluate("//employees/employee/name[text()='Andrew']", doc,
    XPathConstants.NODESET);

//replace all nodes matching with new value
for (int idx = 0; idx < nodes.getLength(); idx++) {
  nodes.item(idx).setTextContent("David");
}

Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(new DOMSource(doc), new StreamResult(new File("data_new.xml")));