Curtis
Curtis

Reputation: 103348

Filter for-each by XML attribute

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> 

Upvotes: 4

Views: 5893

Answers (3)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243459

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

Upvotes: 4

Martin Honnen
Martin Honnen

Reputation: 167571

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.

Upvotes: 4

Treemonkey
Treemonkey

Reputation: 2163

<xsl:variable name="varName">
   <xsl:for-each select="Results/Option[@isDefault='true']">
      <xsl:value-of select="@value" />
   </xsl:for-each>
</xsl:variable> 

Upvotes: 0

Related Questions