Skip to content

Code: XPath

Michaela Iorga edited this page Feb 2, 2024 · 1 revision

XPath

How do I check for multiple kinds of elements at the same time with XPath 3.0?

Let's say we want to look for the following OSCAL syntax elements in XML at the same time:

  • any definition of a field with the name "with-id" in one or more target documents
  • any definition of a flag with the name "pattern" in one or more target documents
  • any definition of an assembly with the name "matching" in one or more target documents

Apply the following query against the target document(s) (for this example any Metaschema definition in src/metaschema/*.xml), observing use of the | ("union") operator:

//(
    define-flag[@name='pattern']
   | define-assembly[@name='matching']
   | define-field[@name='with-id']
 )

Here is a sneakier way to do something similar:

//@name[.=('pattern','matching','with-id')]/parent::*

parent::* can also be shortened to .. for those who prefer.

Mathematically, this path returns a superset of the nodes returned by the first path given, although in a particular metaschema they are likely to be the same.

This takes advantage of a feature of general comparison operators in XPath (=, <, >, <=, >=) namely that they support comparing sequences, i.e. many values on either side of the operand, hence .=('a','b','c').

Clone this wiki locally