Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter for-each by XML attribute

Tags:

xml

xslt

If I have the following XML:

<Results>
  <Option isDefault="true" value="1">
     <DisplayName>
        One
     </DisplayName>
  </Option>
  <Option value="2">
     <DisplayName>
        Two
     </DisplayName>
  </Option>
  <Option value="3">
     <DisplayName>
        Three
     </DisplayName>
  </Option>
</Results>

How can I access the value of the Option which has isDefault="true"?

So far I have tried:

<xsl:variable name="varName">
   <xsl:for-each select="Results/Option[isDefault='true']">
      <xsl:value-of select="@value" />
   </xsl:for-each>
</xsl:variable> 
like image 934
Curtis Avatar asked Oct 16 '25 00:10

Curtis


2 Answers

If you know there is only a single such element or if you are interested only in the first such element you can simply use

<xsl:value-of select="Results/Option[@isDefault = 'true']/@value"/>

there is no need for a for-each. That applies to XSLT 1.0 and value-of, with 2.0 the above would output the value attribute values of all Results/Option[@isDefault = 'true'] elements.

like image 79
Martin Honnen Avatar answered Oct 17 '25 21:10

Martin Honnen


If there is guaranteed to be at most one Option element whose isDefault attribute has the string value of "true",

then use this Xpath one-liner:

/*/*[@isDefault='true']/@value
like image 40
Dimitre Novatchev Avatar answered Oct 17 '25 22:10

Dimitre Novatchev