[英]How to convert XML into CSV using XSL
我有一個像這樣的 XML 文件
<Tester author="Name" id="16384543">
<insert tableName="sampletable">
<column name="id" valueNumeric="2"/>
<column name="name" value="kathy"/>
<column name="active" valueBoolean="true"/>
<column name="age" valueNumeric="2"/>
</insert>
<insert tableName="sampletable">
<column name="id" valueNumeric="23"/>
<column name="name" value="Queen"/>
<column name="active" valueBoolean="true"/>
<column name="age" valueNumeric="29"/>
</insert>
<insert tableName="sampletable">
<column name="id" valueNumeric="25"/>
<column name="name" value="varshan"/>
<column name="active" valueBoolean="false"/>
<column name="age" valueNumeric="5"/>
</insert>
</Tester>
我需要將 XML 轉換為 CSV 如下所示:
id,name,active,age
2,kathy,TRUE,2
23,Queen,TRUE,29
25,varshan,FALSE,5
要求:
這些列屬性將是動態的,並且對於不同的 XML 會有所不同。 有人可以幫忙嗎?
這是一種可以做到的方法。
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
version="1.0">
<xsl:output method="text"/>
<xsl:template match="/">
<!-- Header -->
<xsl:apply-templates select="Tester/insert[1]">
<xsl:with-param name="header">true</xsl:with-param>
</xsl:apply-templates>
<!-- Data -->
<xsl:apply-templates select="Tester/insert"/>
</xsl:template>
<xsl:template match="insert">
<xsl:param name="header"/>
<xsl:for-each select="column">
<!-- For the header take the name attribute, else take the attribute starting with value -->
<xsl:choose>
<xsl:when test="$header='true'">
<xsl:value-of select="@name"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="@*[starts-with(name(),'value')]"/>
</xsl:otherwise>
</xsl:choose>
<!-- Insert comma between values, except for last value insert new line -->
<xsl:choose>
<xsl:when test="position()=last()">
<xsl:text>
</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:text>,</xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
看到它在這里工作: https://xsltfiddle.liberty-development.net/3MXNWN6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.