4

連続して番号が付けられている可能性のある属性値をチェックし、開始値と終了値の間にダッシュを入力する必要がある状況があります。

<root>
<ref id="value00008 value00009 value00010 value00011 value00020"/>
</root>

理想的な出力は...

8-11, 20

属性を個別の値にトークン化することはできますが、「valueXXXXX」の末尾の数字が前の値と連続しているかどうかを確認する方法がわかりません。

XSLT 2.0 を使用しています

4

1 に答える 1

4

を差し引いた値xsl:for-each-group@group-adjacentテストで使用できます。number()position()

Michael Kay によると、このトリックはDavid Carlisleによって考案されたようです。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     version="2.0">
  <xsl:output indent="yes"/>
  <xsl:template match="/">
        <xsl:variable name="vals" 
               select="tokenize(root/ref/@id, '\s?value0*')[normalize-space()]"/>

        <xsl:variable name="condensed-values" as="item()*">

          <xsl:for-each-group select="$vals" 
                              group-adjacent="number(.) - position()">
              <xsl:choose>
                  <xsl:when test="count(current-group()) > 1">
                    <!--a sequence of successive numbers, 
                        grab the first and last one and join with '-' -->
                    <xsl:sequence select="
                               string-join(current-group()[position()=1 
                                              or position()=last()]
                                           ,'-')"/>
                  </xsl:when>
                  <xsl:otherwise>
                      <!--single value group-->
                      <xsl:sequence select="current-group()"/>
                  </xsl:otherwise>
              </xsl:choose>
          </xsl:for-each-group>
        </xsl:variable>

      <xsl:value-of select="string-join($condensed-values, ',')"/>

  </xsl:template>
</xsl:stylesheet>
于 2013-10-19T01:40:17.430 に答える