XSL生成CSV

时间:2013-03-21 11:37:20

标签: xslt csv

尝试转换此内容:

<list>
  <entry>
          <parentFeed>
                    <feedUrl>http://rss.nzherald.co.nz/rss/xml/nzhrsscid_000000001.xml</feedUrl>
                      <id>68</id>
                      </parentFeed>
                          <content>Schools will have to put up with problematic pay administered through Novopay for another eight weeks after the Government announced it would persist with the unstable system.Minister responsible for Novopay, Steven Joyce, delayed...</content>
                          <link>http://www.nzherald.co.nz/nz/news/article.cfm?c_id=1&amp;objectid=10872300&amp;ref=rss</link>
                              <title>Novopay: Govt sticks with unstable system</title>
                              <id>55776</id>
                                  <published class="sql-timestamp">2013-03-19 03:38:55.0</published>
                                  <timestamp>2013-03-19 07:31:16.358 UTC</timestamp>
                                    </entry>
                            </list>

使用XSLT:

Title, Link, Date
Novopay: Govt sticks with unstable system, http://www.nzherald.co.nz/nz/news/article.cfm?c_id=1&objectid=10872300&ref=rss, 2013-03-19 03:38:55.0

但是尽可能地尝试,我无法摆脱文档开头的空白行。我的样式表如下:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:csv="csv:csv"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="text" encoding="UTF-8"/> 
<xsl:template match="/list"> <xsl:for-each select="entry">
Title, Link, Date
<xsl:value-of select="title"/>, <xsl:value-of select="link"/>, <xsl:value-of select="published"/>
</xsl:for-each></xsl:template>
</xsl:stylesheet>

我已尝试按<xsl:text>&#xD;</xsl:text>建议删除最后一个换行符here,因此我将其移至文件顶部,此时它变为无操作。解决方案here实际上添加一个空行(这是有意义的,因为十六进制代码用于换行符,根据ascii manpage)。

作为一种解决方法,我一直在使用Java来生成CSV输出。

但是,我觉得XSLT会更快,因为它旨在将XML转换为各种其他格式。类似的XSLT完美地生成HTML,RSS和ATOM源。

1 个答案:

答案 0 :(得分:3)

你做得很完美,你的逻辑很明显。但是,您需要记住的是,当您输出文本时,XSLT中的所有缩进都会影响输出,因此您的XSLT应如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:csv="csv:csv"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="text" encoding="UTF-8"/>
<xsl:template match="/list"> <xsl:for-each select="entry">Title, Link, Date
<xsl:value-of select="title"/>, <xsl:value-of select="link"/>, <xsl:value-of select="published"/>
<xsl:text>
</xsl:text>
</xsl:for-each></xsl:template>
</xsl:stylesheet>

运行上面的XSLT,它将完美运行。