XPath test syntax

This page should help craft XPath statements to be used within tests.

An XPath test is a structured expression which operates on XML content. It has many operators that can check if a node is present, what the value of the node is and it's attributes.

Other operators allow for numeric or string comparisons.

In most cases, the issues with ODF round-tripping are where XML nodes do not survive the trip so usually a simple count of the nodes will suffice. In this case, the tester would count how many nodes exist in the input document and write XPath to return true on the input document. The same XPath is then executed on the output document and the test will fail if the post-process test does not return a true result.

For example, if you are interested in checking if a text paragraph is maintained, you may want to create a test that checks that at least one occurrence of the paragraph node exists.

A node for a paragraph looks like this:

  • <text:p text:p/>

Elements and attributes

One XPath expression is 'count(//text:style-name)>1'. text:style-name is an attribute. Those are referenced by prefixing them with '@'.

Without the '@', you are referencing an element with that name. So you'd want to use 'count(//@text:style-name)>1' here.

XPath examples

The XPath expression to check that at least one paragraph node exists is:

  • count(//text:p)>1

You may want to check that an exact quantity of paragraph nodes are present:

  • count(//text:p)=3

To check a specific attribute of a node, use this:

  • count(//text:change-start/@text:change-id)=5

To cound the number of cells that span 2 rows:

  • count(//table:table-cell[@table:number-rows-spanned=2])

Some common node names that you may want to use in your tests are:

  • Headings: text:h
  • Images: draw:image
  • Style: office:styles (in styles.xml)

A full list of ODF nodes can be found within the OASIS specification.

Images

Images can be complicated as an application may replace an .svg image with an .svg image and a backup or preview .png image. Therefore the image count may not be as expected so checking for a greater number could be more effective, for example: count(//draw:image)>=1. More complex XPath could also be created to handle this situation.

XPath resources

More complex tests are possible with XPath, for example, test a value, or regular expression. You can find out more here:

  • https://www.w3schools.com/xml/xpath_syntax.asp
  • https://www.tutorialspoint.com/xpath/xpath_expression.htm
  • https://www.w3.org/TR/xpath/