XSLT filter with index counter

I wrote some XSLT that uses one XML document to filter another. Now I would like to assign my output elements with position(), but my filter condition is not built into mine <xsl:for-each>, so position()it gives me results with numbering spaces. How to get rid of gaps?

<xsl:variable name="Astring">
  <a><b>10</b><b>20</b><b>30</b></a>
</xsl:variable>
<xsl:variable name="A" select="msxml:node-set($Astring)" />

<xsl:variable name="Bstring">
  <c><d>20</d><d>30</d></c>
</xsl:variable>
<xsl:variable name="B" select="msxml:node-set($Bstring)" />

<e>
  <xsl:for-each select="$A/a/b">
    <xsl:variable name="matchvalue" select="text()" />
    <xsl:if test="count($B/c/d[text() = $matchvalue]) &gt; 0">
      <xsl:element name="f">
        <xsl:attribute name="i">
          <xsl:value-of select="position()" />
        </xsl:attribute>
        <xsl:copy-of select="text()" />
      </xsl:element>
    </xsl:if>
  </xsl:for-each>
</e>

Here is the result:

<e>
  <f i="2">20</f>
  <f i="3">30</f>
</e>

... but I want this:

<e>
  <f i="1">20</f>
  <f i="2">30</f>
</e>

Is there a way to enable the filtering test described above <xsl:if>inside an attribute <xsl:for-each> select?

Note: I saw this question re: filtering and this one : counters, but the former does not count its results, and the latter uses position ().

+3
source share
2

- , for-each?

<xsl:for-each select="$A/a/b[$B/c/d = .]">

Visual Studio .

:

<e>
  <f i="1">20</f>
  <f i="2">30</f>
</e>
+3

, <xsl:for-each>, <xsl:apply-templates>, , .

, . , : <xsl:for-each> . . for-each:

<xsl:template match="/">
  <e><xsl:apply-templates select="$B/c/d[$A/a/b = .]" /></e>
</xsl:template>

<xsl:template match="d">
  <f i="{position()}"><xsl:value-of select="." /></f>
</xsl:template>

:

<e>
  <f i="1">20</f>
  <f i="2">30</f>
</e>

, . <xsl:for-each>:

<xsl:template match="/">
  <e>
    <xsl:for-each select="$B/c/d[$A/a/b = .]">
      <f i="{position()}"><xsl:value-of select="." /></f>
    </xsl:for-each>
  </e>
</xsl:template>

, <xsl:apply-templates>, IMHO.

+2

Source: https://habr.com/ru/post/1705173/


All Articles