[英]How to produce a near csv format using xsl?
我有以下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格式?
對於CSV輸出,您需要在XSLT中指定<xsl:output method="text"/>
。 如果要查找包含<cd>
的所有子元素的comma
分隔值的輸出,則可以使用以下任何一種方法。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.