【问题标题】:XSL - combine for each with textXSL - 将每个与文本结合起来
【发布时间】:2015-12-13 13:16:35
【问题描述】:

大家好,我有一个关于 for each 循环的问题。 我想在任何匹配后添加一个文本序列。目前我只得到文本和整个匹配项。知道为什么吗?

这是我的 XML 文件,例如:

    <?xml version="1.0" encoding="UTF-8"?>
<catalog>
    <cd>
        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
                <country>DE</country>
                <country>AUT</country>
        <company>Columbia</company>
        <price>10.90</price>
        <year>1985</year>
    </cd>
</catalog>

这是我的 XML 转换:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <html>
  <body>
      <xsl:for-each select="catalog/cd">
      <xsl:value-of select="country" />
      <xsl:text> and </xsl:text>
      </xsl:for-each>
  </body>
  </html>
</xsl:template>

</xsl:stylesheet>

这是我的结果和我的问题:

USA and 

预期的输出应该是:

USA and DE and AUT

我确信这是一个初学者的错误并且很容易解决,但我不知道如何以简单的方式解决它。提前致谢

【问题讨论】:

    标签: xml xslt foreach


    【解决方案1】:

    这是一种可能的方式:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
    <xsl:template match="/">
      <html>
      <body>
          <xsl:for-each select="catalog/cd/country">
              <xsl:value-of select="." />
              <xsl:if test="position() &lt; last()">
                  <xsl:text> and </xsl:text>
              </xsl:if>
          </xsl:for-each>
      </body>
      </html>
    </xsl:template>
    
    </xsl:stylesheet>
    

    xsltransform demo

    简要说明:

    • 您可以使用点 (.) 来引用当前上下文元素
    • &amp;lt; 是小于号字符 &lt; 的编码版本
    • xsl:for-each 部分循环通过country 元素,而不是像您最初那样循环使用cd。并在循环内检查当前country位置索引是否小于(&lt;)最后一个索引,如果是则将文本" and "附加到country的值,否则仅输出该值。

    【讨论】:

    • 非常感谢,这正是我要找的
    猜你喜欢
    • 2021-09-28
    • 2020-02-03
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 2023-03-22
    • 2018-09-30
    相关资源
    最近更新 更多