Change a particular node in XML

From CodeCodex

Implementations[edit]

Java[edit]

Consider this XML file.

<data>
 <employee>
    <name>John</name>
    <title>Manager</title>
 </employee>
 <employee>
    <name>Sara</name>
    <title>Clerk</title>
    </employee>
</data>


We want to change employee named "John" to "John Paul" You locate the element to change with an XPath query. You change the text and then save back the data.

import java.io.File;

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 javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class XMLReplaceDemo {
  static String inputFile = "C:/temp/data.xml";
  static String outputFile = "C:/temp/data_new.xml";

  public static void main(String[] args) throws Exception {
    Document doc = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder().parse(new InputSource(inputFile));

    // locate the node(s)
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList)xpath.evaluate
        ("//employee/name[text()='John']", doc, XPathConstants.NODESET);

    // make the change
    for (int idx = 0; idx < nodes.getLength(); idx++) {
      nodes.item(idx).setTextContent("John Paul");
    }
 
    // save the result
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform
        (new DOMSource(doc), new StreamResult(new File(outputFile)));
  }
}


The result

<?xml version="1.0" encoding="UTF-8" standalone="no"?><data>
 <employee>
    <name>John Paul</name>
    <title>Manager</title>
 </employee>
 <employee>
    <name>Sara</name>
    <title>Clerk</title>
    </employee>
</data>