Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xsl select node based on number value

I have an xml document that I am trying to style with xsl. The problem is depending on the value I need to pull from a certain node, but in xsl I do not know how to distinguish between the two following nodes:

XML:

<a number=1>
<car>1</car>
</a>

<a number=2>
<dog>1</dog>
</a>

<I_want_to_display>
<number>2</number>
</I_want_to_display>

XSL:

 <xsl:for-eachselect="I_want_to_display">
      <xsl:if test="number==2">
      ....display everything in <a number=2>
      </xsl:if>
like image 587
tdjfdjdj Avatar asked Mar 01 '26 04:03

tdjfdjdj


1 Answers

Without knowing exactly what output you're looking for, but here's a guess.

This well-formed XML input:

<xml>
  <a number="1">
    <car>1</car>
  </a>

  <a number="2">
    <dog>1</dog>
  </a>

  <I_want_to_display>
    <number>2</number>
  </I_want_to_display>
</xml>

with this stylesheet:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="node()|@*">
    <xsl:apply-templates select="node()|@*"/>
  </xsl:template>

  <xsl:template match="I_want_to_display">
    <xsl:variable name="vNbr" select="number/text()"/>
    <xsl:copy-of select="//*[normalize-space(@number) = $vNbr]"/>
  </xsl:template>

</xsl:stylesheet>

produces this output:

<a number="2">
   <dog>1</dog>
</a>
like image 88
Daniel Haley Avatar answered Mar 03 '26 03:03

Daniel Haley



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!