我有这个 xslt 将 csv 转换为 xml,工作正常,除了所有列的标签都相同。我需要它像这样增加
<row>
<column1></column1>
<column2></column2>
<column3></column3>
</row>
当我使用 position() 时,它将所有列重命名为 column1
<xsl:element name="{concat('column', position())}">
这是xslt:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes"/>
<xsl:variable name="LF" select="'
'"/>
<!-- template that matches the root node-->
<xsl:template match="/">
<root>
<xsl:call-template name="texttorows">
<xsl:with-param name="StringToTransform" select="/root"/>
</xsl:call-template>
</root>
</xsl:template>
<!-- template that actually does the conversion-->
<xsl:template name="texttorows">
<!-- import $StringToTransform-->
<xsl:param name="StringToTransform" select="''"/>
<xsl:choose>
<!-- string contains linefeed-->
<xsl:when test="contains($StringToTransform,$LF)">
<!-- Get everything up to the first carriage return-->
<row>
<xsl:call-template name="csvtoxml">
<xsl:with-param name="StringToTransform" select="substring-before($StringToTransform,$LF)"/>
</xsl:call-template>
</row>
<!-- repeat for the remainder of the original string-->
<xsl:call-template name="texttorows">
<xsl:with-param name="StringToTransform">
<xsl:value-of select="substring-after($StringToTransform,$LF)"/>
</xsl:with-param>
</xsl:call-template>
</xsl:when>
<!-- string does not contain newline, so just output it-->
<xsl:otherwise>
<row>
<xsl:call-template name="csvtoxml">
<xsl:with-param name="StringToTransform" select="$StringToTransform"/>
</xsl:call-template>
</row>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template name="csvtoxml">
<!-- import $StringToTransform-->
<xsl:param name="StringToTransform" select="''"/>
<xsl:choose>
<!-- string contains linefeed-->
<xsl:when test="contains($StringToTransform,',')">
<!-- Get everything up to the first carriage return-->
<xsl:element name="{concat('column', position())}">
<xsl:value-of select="substring-before($StringToTransform,',')"/>
</xsl:element>
<!-- repeat for the remainder of the original string-->
<xsl:call-template name="csvtoxml">
<xsl:with-param name="StringToTransform">
<xsl:value-of select="substring-after($StringToTransform,',')"/>
</xsl:with-param>
</xsl:call-template>
</xsl:when>
<!-- string does not contain newline, so just output it-->
<xsl:otherwise>
<column>
<xsl:value-of select="$StringToTransform"/>
</column>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
这是一个示例 csv:
<root>
3779490,916705,CS,60,34.89,Sauce/Cholula
5918104,918958,CS,6,20.63,Pasta/Fresh/Cavatelli/6#/Frozen
5064774,920723,CS,10,45.5,Cheese/Oaxaca
3422752,925230,EA,8,69.6,Chipotle/Powder/Ground
5955640,BB171,CS,30,50.7,Butter/Unsalted
5295326,BC110005,CS,6000,54.95,Oil/Olive/Finishing
</root>