Skip to content
Stefan Bodewig edited this page Jan 23, 2016 · 13 revisions

Obtaining the Results of an XPath Query

The (I)XPathEngine interface inside the xpath/XPath package/namespace provides two pairs of methods that apply an XPath expression to a piece of XML and return the result as a string or collection of DOM nodes.

The first pair expects the "piece of XML" to be provides as (I)Source like most other code in XMLUnit as well, the second pair directly works on DOM nodes. Initially only the Source-arg versions existed, but the underlying implementations can work efficiently on nodes directly, so the overloads have been added.

For Java as well as .NET only a single implementation of the XPathEngine interface exists - they use javax.xml.xpath and System.Xml.XPath under the covers directly. In the Java case all checked exceptions will be transformed to runtime exceptions.

In order to use namespace prefixes inside the XPath expressions you need to provide a NamespaceContext.

Currently there is no Matcher or Constraint that would make writing tests more convenient. If you'd like to help out, please tell us about it.

Examples:

Selecting nodes:

Iterable<Node> i = new JAXPXPathEngine().selectNodes("//li", source);
assertNotNull(i);
int count = 0;
for (Iterator<Node> it = i.iterator(); it.hasNext(); ) {
    count++;
    assertEquals("li", it.next().getNodeName());
}
assertEquals(4, count);

in Java. For .NET it would be

IEnumerable<XmlNode> i = new XPathEngine().SelectNodes("//li", source);
Assert.IsNotNull(i);
int count = 0;
foreach (XmlNode n in i) {
    count++;
    Assert.AreEqual("li", n.Name);
}
Assert.AreEqual(4, count);

Evaluating an XPath to a string:

assertEquals("Don't blame it on the...",
             new JAXPXPathEngine().evaluate("//title", source));

in Java. For .NET it would be

Assert.AreEqual("Don't blame it on the...",
                new XPathEngine().Evaluate("//title", source));
Clone this wiki locally