如何使用XSL将液化XML转换为CSV



以下是生成的XML:

XML:

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext" xmlns:pro="http://www.liquibase.org/xml/ns/pro" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd http://www.liquibase.org/xml/ns/pro http://www.liquibase.org/xml/ns/pro/liquibase-pro-4.1.xsd"> 
<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>
</databaseChangeLog>

我需要将XML转换为CSV,如下所示:id,name,active,age2,凯西,真的,223,女王,真实,2925,varshan,假,5

要求:这些列属性将是动态的,并且对于不同的XML它们将不同。有人能帮忙吗?

添加到我在这里提供的答案中:如何使用XSL 将XML转换为CSV

您需要考虑命名空间。

<?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"
xmlns:dbc="http://www.liquibase.org/xml/ns/dbchangelog"
version="1.0">
<xsl:output method="text"/>
<xsl:template match="/">
<!-- Header -->
<xsl:apply-templates select="dbc:databaseChangeLog/dbc:Tester/dbc:insert[1]">
<xsl:with-param name="header">true</xsl:with-param>
</xsl:apply-templates>
<!-- Data -->
<xsl:apply-templates select="dbc:databaseChangeLog/dbc:Tester/dbc:insert"/>
</xsl:template>

<xsl:template match="dbc:insert">
<xsl:param name="header"/>
<xsl:for-each select="dbc: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>&#xa;</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/aB9NK5

最新更新