Xpath query with multiple nodes at different levels

1.3k Views Asked by At

I need a Xpath query to find a XML file with certain nodes. The nodes are located at different levels in the XML file, under different parents. So, it would be like if I want to recover a file like the one below using the nodes "author" and "ref year =1999".

<FILE>
    <header>
        <author> X </author>
    </header>
    <text>
        <type>
            <ref year="1999">
        </type>
    </text>
</FILE>

The only difference is that the XML I'm using have a much more complex structure, so it would be ideal if I could use a "//" to find the nodes anywhere, instead of using the exact path. I can't use the | operator to join the two nodes, because I want to find the files which satisfy both conditions and not only one.

Thanks!

1

There are 1 best solutions below

0
kjhughes On

This XPath,

//FILE[header/author="X" and text/type/ref/@year="1999"]

will select FILE elements anywhere in the document that meet the conditions in the predicate.

Use or rather than and if you want a disjunctive predicate. (Note that | is used to concatenate node sets.) Combinations of and, or, and not() can be used to express full boolean expressions in the predicate.

If the structure beneath FILE itself varies, you can use .// to "skip over" the variations. For example,

//FILE[.//author="X" and .//ref/@year="1999"]

will disregard the path between FILE and each of author and ref/@year.