Compare attribute values ​​using Xpath

Given the following document structure, how can I check if two attribute values ​​match using Xpath?

<document lang="en">
<element lang="en"></element>
<element lang="sv"></element>
<element lang="fr"></element>
</document>

      

What I'm looking for is something like:

//document[@lang="[//element[@lang]"]

      

+3


source to share


4 answers


This will return all nodes <document>

that have an attribute value lang

that matches any child node attribute <element>

lang

:



//document[@lang = element/@lang]

      

+4


source


Specifically, for your example, you can use:

//document[@lang=child::element/@lang]

      

If you are just checking if a match exists, you can wrap it in boolean

:

boolean(//document[@lang=child::element/@lang])

      

If you want to select the appropriate item, you can check it for ancestor

:



//element[@lang=ancestor::document[1]/@lang]

      

If you want to map any nodes to matching attributes elsewhere, you can do something like this:

//node()[@lang=following::node()/@lang]

      

This should match the first node that matches elsewhere in the document.

+1


source


This example should work:

//document/@lang[. = //element/@lang]

      

0


source


XPath is a query language. Its main use is to find XML nodes, not "check" if such and such a condition is true or not.

A similar task is better suited for a host language that has XPath embedded in it, such as XSLT. XSLT has an element for this xsl:if

.

For example write a template like

<xsl:template match="/document">
  <xsl:if test="@lang = element/@lang">
    <true/>
  </xsl:if>
</xsl:template>

      

The template above matches document

and returns the element <true/>

if the element's attribute value element

matches the value document/@lang

.

0


source







All Articles