大家好,我对每个循环都有疑问。 我希望在任何匹配后添加文本序列。目前我只收到文字和整场比赛。知道为什么吗?
这是我的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
我确信这是一个初学者的错误,很容易解决,但我不知道如何以一种简单的方式解决这个问题。提前谢谢
答案 0 :(得分: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() < last()">
<xsl:text> and </xsl:text>
</xsl:if>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
<强> xsltransform demo
强>
简要说明:
.
)来引用当前上下文元素<
是小于号码字符<
xsl:for-each
部分会像您最初那样循环遍历country
元素,而不是cd
。在循环内部,它检查当前country
位置索引是否小于(<
)最后一个索引,如果是,则将文本" and "
追加到country
的值,否则只输出该值。