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>


What I'm looking for is something like:




source to share

4 answers

This will return all nodes <document>

that have an attribute value lang

that matches any child node attribute <element>



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




Specifically, for your example, you can use:



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




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




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



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



This example should work:

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




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">


The template above matches document

and returns the element <true/>

if the element's attribute value element

matches the value document/@lang




All Articles