代码之家  ›  专栏  ›  技术社区  ›  aw1975

XSLT-将XML输入转换为具有两列的HTML表

  •  0
  • aw1975  · 技术社区  · 6 年前

    这是我的源XML文件:

    <?xml version="1.0" encoding="utf-8"?>
    <root>
      <employees>
        <region>
          <country>AUS</country>
          <count>3</count>
        </region>
        <region>
          <country>BEL</country>
          <count>1</count>
        </region>
        <region>
          <country>PER</country>
          <count>1</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">
      <entry key="AGO">Angola</entry>
      <entry key="ALA">Alaska</entry>
      <entry key="AUS">Australia</entry>
      <entry key="PER">Peru</entry>
      <entry key="NKO">Not Known</entry>
      </xsl:variable>
        <xsl:template match="employees">
        <html>
            <body>
            <div>
              <table>
                <xsl:variable name="test" select="region[count &gt; 0]"></xsl:variable>
                <xsl:for-each select="$test[position() mod 2 = 1]">
                  <tr>
                    <td>
                      <xsl:variable name="countryLeft" select="country"></xsl:variable>
                      <xsl:value-of select="msxsl:node-set($map)/entry[@key=$countryLeft]"/>
                    </td>
                    <td>
                      <xsl:variable name="countryRight" select="following-sibling::region/country"></xsl:variable>
                      <xsl:value-of select="msxsl:node-set($map)/entry[@key=$countryRight]"/>
                    </td>
                  </tr>
                </xsl:for-each>
              </table>
            </div>
          </body>
          </html>
        </xsl:template>
    </xsl:stylesheet>
    

    XSLT应该从XML中每隔两个区域获取一个区域,并将它们显示在一个表行中,表行中有两列,每个区域一列。它还应将源国家代码映射到相应的显示名称。在本例中,我将国家地图存储在名为 map ,但我也可以从另一个XML文件(使用 document()

    Australia | Belgium
    --------------------
    Peru      |  Alaska
    

    但它正在回归:

    Australia | Alaska
    ------------------
    Peru      |  Alaska
    

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

    我在XSLT方面没有太多经验,因此希望您能给我一些指导,告诉我哪里出了问题。

    1 回复  |  直到 6 年前
        1
  •  1
  •   michael.hor257k    6 年前

    恐怕我对此没有很好的解释,但如果您改变:

    <xsl:variable name="countryRight" select="following-sibling::region/country"></xsl:variable>
    

    致:

    <xsl:variable name="countryRight" select="following-sibling::region[1]/country"></xsl:variable>
    

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