Java HTML / XML How to - Update multiple nodes via XPATH that need different values








Question

We would like to know how to update multiple nodes via XPATH that need different values.

Answer

import java.io.File;
/*  w w  w.j  a  v a 2  s  . c  o  m*/
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new File("path/to/file.xml"));

    XPathFactory xFactory = XPathFactory.newInstance();
    XPath xPath = xFactory.newXPath();
    XPathExpression expression = xPath
        .compile("PersonList/Person/Age/text() | PersonList/Person/Name/text()");

    NodeList nodes = (NodeList) expression
        .evaluate(doc, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
      Node node = nodes.item(i);
      if (node.getParentNode().getNodeName().equals("Name")) {
        node.setNodeValue("new name");
      } else {
        node.setNodeValue("42");
      }
    }
  }
}

path/to/file.xml

<?xml version="1.0" encoding="UTF-8"?>  
<PersonList>  
    <Person>  
          <Name>old Name</Name>  
          <Age> 72 </Age>
    </Person>  
</PersonList>