简体   繁体   中英

What is the meaning of the following expression in xPath?

Can someone help me to understand how to read the following expression in xpath? what is the meaning of this expression?
//*/id(@*)/*

It's a strange and cryptic expression, but I'll try to decipher it.

The initial // is an abbreviation for /descendant-or-self::node()/ and * refers to elements with any name. So this selects every element which is a descendant of the root (ie all the elements in the document).

The next part, /id(@*) , takes that sequence of elements and evaluates the function call id(@*) for each one. This is the complicated part:

If the element has at least one attribute, then the expression @* will produce a sequence of attributes which will passed to the id() function, which will return a sequence of elements in the document whose ID matches one of the tokens in the attribute values in the sequence (NB an attribute like link="xyz" will contribute 3 tokens 'x', 'y', and 'z'). So if your document has an element like <a reference1="b" reference2="cd"/> , then the id() function will return elements which have the ID property of b or c or d , eg <c xml:id='c'/> would be returned if it were in the document.

If the element has no attributes, then the expression @* returns an empty sequence, and I think in that case the id() function will use the value of the context node instead. So an element like <b>c</b will pass 'c' to the id() function, unlike an element like <b ref="foo">c</b> , which will pass 'foo'.

So essentially this second step returns elements which have an ID referred to by any attribute of any element in the document.

The final step /* of the path would simply return the child elements of the elements returned from that second step.

For example, with this document:

<test>
  <a xml:id="a">
    <b/>
  </a>
  <c xml:id="c">
    <d/>
  </c>
  <e xml:id="e">
    <f/>
  </e>
  <g ref="a" ref2="c"/>
  <h>e</h>
</test>

... evaluating //*/id(@*)/* should return this result:

<b/>
<d/>
<f/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM