Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select an attribute based on another attribute's value

Tags:

xml

xslt

xpath

I need to select the NativeDescription value when Credit_Term_Code="4" by looping in XSLT:

<Credit_code_parents>
  <Credit_Term_parent Credit_Term_Code="1" NativeDescription="Letter of Credit" EnglishDescription="Letter of Credit" />
  <Credit_Term_parent Credit_Term_Code="2" NativeDescription="Cash on Delivery" EnglishDescription="Cash on Delivery" />
  <Credit_Term_parent Credit_Term_Code="3" NativeDescription="Contract" EnglishDescription="Contract" />
  <Credit_Term_parent Credit_Term_Code="4" NativeDescription="Net" EnglishDescription="Net" />
  <Credit_Term_parent Credit_Term_Code="5" NativeDescription="Contract" EnglishDescription="Contract" />
  <Credit_Term_parent Credit_Term_Code="6" NativeDescription="Net" EnglishDescription="Net" />
  <Credit_Term_parent Credit_Term_Code="7" NativeDescription="Contract" EnglishDescription="Contract" />
  <Credit_Term_parent Credit_Term_Code="8" NativeDescription="Net" EnglishDescription="Net" />
</Credit_code_parents>
like image 822
Rams Avatar asked Dec 03 '25 09:12

Rams


1 Answers

To select the NativeDescription attribute of the Credit_Term_parent element with a Credit_Term_Code equal to 4, use one of the following XPaths:

  1. If the ancestral structure above Credit_Term_parent is fixed as shown:

    /Credit_code_parents/Credit_Term_parent[@Credit_Term_Code='4']/@NativeDescription
    
  2. If there's potentially variable ancestral structure above Credit_Term_parent (and assuming that the provided Credit_Term_Code is unique across the document):

    //Credit_Term_parent[@Credit_Term_Code='4']/@NativeDescription
    

You ask for XSLT looping code:

<xsl:for-each select="/Credit_code_parents/Credit_Term_parent">
   <xsl:if test="@Credit_Term_Code=4">
     <xsl:value-of select="@Credit_Term_parent"/>
   </xsl:if>
</xsl:for-each>

Or, without the loop:

 <xsl:value-of
          select="//Credit_Term_parent[@Credit_Term_Code='4']/@NativeDescription"/>

...or, alternatively, use the XPath from #1 above instead of the one from #2.

like image 127
kjhughes Avatar answered Dec 05 '25 01:12

kjhughes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!