我有以下xsl文件来生成csv格式的cd数据:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/catalog">
<xsl:for-each select="cd">
<xsl:apply-templates/>
<xsl:if test="position() = last()"><xsl:value-of select="./child::*"/>, </xsl:if>
<xsl:if test="position() = last()"><xsl:value-of select="./child::year"/>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
以下是示例数据:
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<cd>
<title>Red</title>
<artist>The Communards</artist>
<country>UK</country>
<company>London</company>
<price>7.80</price>
<year>1987</year>
</cd>
<cd>
<title>Unchain my heart</title>
<artist>Joe Cocker</artist>
<country>USA</country>
<company>EMI</company>
<price>8.20</price>
<year>1987</year>
</cd>
</catalog>
每次我在氧气上运行程序时都会遇到一种悲惨的格式:如何调整输出以产生csv格式?
答案 0 :(得分:1)
对于CSV输出,您需要在XSLT中指定<xsl:output method="text"/>
。如果您要查找包含comma
所有子元素的<cd>
个分隔值的输出,则可以使用以下任一方法。
XSLT 1.0
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />
<xsl:strip-space elements="*" />
<xsl:template match="cd">
<xsl:for-each select="*">
<xsl:value-of select="." />
<xsl:if test="position() != last()" >
<xsl:text>, </xsl:text>
</xsl:if>
<xsl:if test="position() = last()" >
<xsl:text>
</xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
XSLT 2.0
此版本提供了更优化的解决方案及其附带的附加功能。
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="text" />
<xsl:strip-space elements="*" />
<xsl:template match="cd">
<xsl:value-of select="*" separator=", " />
<xsl:text>
</xsl:text>
</xsl:template>
</xsl:stylesheet>
输出
Red, The Communards, UK, London, 7.80, 1987
Unchain my heart, Joe Cocker, USA, EMI, 8.20, 1987