这篇文章向您展示如何使用XSLT将简单的XML文件转换为CSV。
考虑以下示例XML:
<library>
<book>
<author>Dan Simmons</author>
<title>Hyperion</title>
<publishDate>1989</publishDate>
</book>
<book>
<author>Douglas Adams</author>
<title>The Hitchhiker's Guide to the Galaxy</title>
<publishDate>1979</publishDate>
</book>
</library>
这是所需的CSV输出:
author,title,publishDate
Dan Simmons,Hyperion,1989
Douglas Adams,The Hitchhiker's Guide to the Galaxy,1979
以下XSL样式表(与XSLT 1.0兼容)可用于将XML转换为CSV。 它非常通用,可以通过更改开头定义的字段列表轻松配置为处理不同的xml元素。
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />
<xsl:variable name="delimiter" select="','" />
<!-- define an array containing the fields we are interested in -->
<xsl:variable name="fieldArray">
<field>author</field>
<field>title</field>
<field>publishDate</field>
</xsl:variable>
<xsl:param name="fields" select="document('')/*/xsl:variable[@name='fieldArray']/*" />
<xsl:template match="/">
<!-- output the header row -->
<xsl:for-each select="$fields">
<xsl:if test="position() != 1">
<xsl:value-of select="$delimiter"/>
</xsl:if>
<xsl:value-of select="." />
</xsl:for-each>
<!-- output newline -->
<xsl:text>
</xsl:text>
<xsl:apply-templates select="library/book"/>
</xsl:template>
<xsl:template match="book">
<xsl:variable name="currNode" select="." />
<!-- output the data row -->
<!-- loop over the field names and find the value of each one in the xml -->
<xsl:for-each select="$fields">
<xsl:if test="position() != 1">
<xsl:value-of select="$delimiter"/>
</xsl:if>
<xsl:value-of select="$currNode/*[name() = current()]" />
</xsl:for-each>
<!-- output newline -->
<xsl:text>
</xsl:text>
</xsl:template>
</xsl:stylesheet>
让我们尝试一下:
$ xsltproc xml2csv.xsl books.xml
author,title,publishDate
Dan Simmons,Hyperion,1989
Douglas Adams,The Hitchhiker's Guide to the Galaxy,1979
翻译自: https://www.javacodegeeks.com/2014/07/converting-xml-to-csv-using-xslt-1-0.html