How to store dynamically values in array using XSL

2019-09-21 11:53发布

Below is a good example, but how can I store values dynamically....Could you please explain?

 <xsl:variable name="countries" select="'EG, KSA, UAE, AG'" />
   <xsl:variable name="country"   select="'KSA'" />
     <xsl:choose>
      <xsl:when test="
      contains(
       concat(', ', normalize-space($countries), ', ')
        concat(', ', $country, ', ')
       )
     ">
 <xsl:text>IN</xsl:text>
 </xsl:when>
 <xsl:otherwise>
 <xsl:text>OUT</xsl:text>
</xsl:otherwise>

Look good....I have some another requirement. Could you please look into this?

 <xml>
   <test>
    <BookID>
      0061AB
    </BookID>
    <amount>
      16
    </amount>
   </test>
   <test>
    <BookID>
      0062CD
    </BookID>
    <amount>
      2
    </amount>
   </test>
   <test>
    <BookID>
      0061AB
    </BookID>
    <amount>
      2
    </amount>
   </test>
 </xml>

here According to the equal value of BookID, I want to add the amount value.....like for above example, if value of BookID is 0061AB, then the value of amount should be 18.

标签: xslt
1条回答
Luminary・发光体
2楼-- · 2019-09-21 12:40

As others have mentioned, your question isn't very clear, but you can use a call template to reuse your 'country find' algorithm across an xml document containing both the candidate country and the search list (you could also use document to load split the candidate and search target into separate xml documents)

e.g. when applying the XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:template match="/xml">
    <xsl:apply-templates select="test"/>
  </xsl:template>

  <xsl:template match="test">
    <xsl:call-template name="FindCountry">
      <xsl:with-param name="countries" select="normalize-space(countries/text())"/>
      <xsl:with-param name="country" select="normalize-space(country/text())"/>
    </xsl:call-template>
  </xsl:template>

  <xsl:template name="FindCountry" xml:space="default">
    <xsl:param name="countries" />
    <xsl:param name="country" />
    Is <xsl:value-of select="$country" /> in <xsl:value-of select="$countries" /> ?
    <xsl:choose>
      <xsl:when test="contains(concat(', ', $countries, ', '),
                               concat(', ', $country, ', '))">
        <xsl:text>IN</xsl:text>
      </xsl:when>
      <xsl:otherwise>
        <xsl:text>OUT</xsl:text>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
</xsl:stylesheet>

To the XML

<xml>
  <test>
    <countries>
      EG, KSA, UAE, AG
    </countries>
    <country>
      UAE
    </country>
  </test>
  <test>
    <countries>
      GBR, USA, DE, JP
    </countries>
    <country>
      AUS
    </country>
  </test>
</xml>

Result

Is UAE in EG, KSA, UAE, AG ? IN 
Is AUS in GBR, USA, DE, JP ? OUT
查看更多
登录 后发表回答