XPath on w3c dom nodes

April 16, 2018

In one of my tests I wanted to parse some XML then use XPATH to find a particular node inside the XML. The code was parsing the XML into a org.dom.w3c.Document instance. I then needed to compare the text values of the nodes with expected values.

This can be done with the following code:

Document document = parser.parse(new InputSource(new StringReader(xmlAsString)));

XPath xPath = XPathFactory.newInstance().newXPath(); 
String xPathExpression = "//Individuals/individual";
Element individualNode = (Element) xPath.evaluate(xPathExpression, document.getDocumentElement(), XPathConstants.NODE);

assertEquals(FIRST_NAME, this.getValueFromNodeList(individualNode, "firstName") );
assertEquals(LAST_NAME, this.getValueFromNodeList(individualNode, "lastName"));
assertEquals(NI_NUMBER, this.getValueFromNodeList(individualNode, "niNumber"));
assertEquals(DATE_OF_BIRTH, this.getValueFromNodeList(individualNode, "dateOfBirth"));

The supporting method to get a known value from the NodeList is:

private String getValueFromNodeList(Element individualNode, String name) {
  NodeList nodeList = individualNode.getChildNodes();
  for (int i = 0; i < nodeList.getLength(); i++) {
    Node eachNode = nodeList.item(i);

    if (eachNode.getNodeName().equals(name)) {
      return eachNode.getTextContent();
    }
  }
}