首页 > 解决方案 > XSLT 后续兄弟意外结果

问题描述

这是我的 XML:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <employees>
    <region>
      <country>AUS</country>
      <count>1</count>
    </region>
    <region>
      <country>BEL</country>
      <count>0</count>
    </region>
    <region>
      <country>PER</country>
      <count>3</count>
    </region>
    <region>
      <country>ALA</country>
      <count>5</count>
    </region>
  </employees>
</root>

这是我的 XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
  <xsl:variable name="map">
  </xsl:variable>
    <xsl:template match="employees">
    <html>
        <body>
          <table>
            <xsl:variable name="regionsWithNonZeroCount" select="region[count &gt; 0]"></xsl:variable>
            <xsl:for-each select="$regionsWithNonZeroCount[position() mod 2 = 1]">
              <tr>
                <td><xsl:value-of select="country"/></td>
                <td><xsl:value-of select="following-sibling::region/country"/></td>   
              </tr>
            </xsl:for-each>
          </table>
      </body>
      </html>
    </xsl:template>
</xsl:stylesheet>

XSLT 应该首先排除所有计数不大于 0 的区域(即它应该排除 BEL),并且从其余区域中,它应该一次占用两个并将它们显示在具有两列的表格行中,每个区域一个。

这是我期待的结果:

AUS | PER
-----------
ALA | 

然而实际结果如下:

AUS | BEL
-----------
ALA | 

这是一个演示该问题的 XSLT 小提琴:

https://xsltfiddle.liberty-development.net/eiZQaGp/9

我不明白为什么regionsWithNonZeroCount在循环中迭代的变量不xsl:for-each应该包含 BEL 时输出 BEL。我怀疑following-sibling没有考虑应该排除 BELselect的变量的条件。regionsWithNonZeroCount我对 XSLT 没有太多经验,因此对于如何实现我想要的结果的任何建议将不胜感激。

标签: xsltxpathxslt-1.0

解决方案


你的怀疑是正确的。要获得您想要的结果,请尝试:

<xsl:template match="employees">
    <html>
        <body>
            <table>
                <xsl:variable name="regionsWithNonZeroCount" select="region[count > 0]"/>
                <xsl:for-each select="$regionsWithNonZeroCount[position() mod 2 = 1]">
                    <xsl:variable name="i" select="position()" />
                    <tr>
                        <td>
                            <xsl:value-of select="country"/>
                        </td>
                        <td>
                            <xsl:value-of select="$regionsWithNonZeroCount[2*$i]/country"/>
                        </td>   
                    </tr>
                </xsl:for-each>
            </table>
        </body>
    </html>
</xsl:template>

推荐阅读