使用XSLT进行XML到CSV转换
问题描述:
我正尝试使用xslt将XML转换为csv,因此我不熟悉xslt,因此只是阅读了一些教程和其他在线资源。 这里是我的XML使用XSLT进行XML到CSV转换
<?xml version="1.0" encoding="UTF-8"?>
<impex>
<test>
<Employee />
<UID>auma</UID>
<Name>HR Manager</Name>
<Groups />
<Password>228781</Password>
</test>
<test>
<Employee />
<UID>auma1</UID>
<Name>HR Manager</Name>
<Groups />
<Password>2287811</Password>
</test>
</impex>
我使用的XML转换以下XSL到csv
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:f="Functions"
version="2.0">
<xsl:output method="text" />
<xsl:param name="headerVal" select="'INSERT_UPDATE Employee;UID[unique=true];name;groups(uid);password'"/>
<xsl:template match="/impex">
<xsl:apply-templates select="test[1]/*" mode="header"/>
<xsl:apply-templates select="test" />
</xsl:template>
<xsl:template match="*" mode="header" >
<xsl:value-of select="$headerVal" />
</xsl:template>
<xsl:template match="test">
<xsl:apply-templates select="*"/>
</xsl:template>
<xsl:template match="*" >
<xsl:value-of select="."/>
<xsl:choose>
<xsl:when test="position()=last()">
<xsl:text> </xsl:text>
</xsl:when>
<xsl:otherwise>;</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
我试图使用来定义我的CSV头,但这个工作不适合我
CSV输出
INSERT_UPDATEEmployeeUID[unique=true]namegroups(uid)password
INSERT_UPDATEEmployeeUID[unique=true]namegroups(uid)password
INSERT_UPDATEEmployeeUID[unique=true]namegroups(uid)password
INSERT_UPDATEEmployeeUID[unique=true]namegroups(uid)password
INSERT_UPDATEEmployeeUID[unique=true]namegroups(uid)password
;auma;HR Manager;;228781
;auma1;HR Manager;;2287811
如下线
<xsl:param name="headerVal" select="'INSERT_UPDATE Employee;UID[unique=true];name;groups(uid);password'"/>
我是假设它在select
值;
是因为,但我即使去掉它,甚至删除的空间,但没有任何帮助 我用Google搜索关于这一点,但无法找到一种方式,如何定义这个报头我的XSL文件里,这样我可以提前用这个头我的CSV
感谢
答
问题解决。
<xsl:apply-templates select="test[1]/*" mode="header"/>
这里我选择内部test[1]
,在我的XML的所有元素我有test
元素内五行,所以我只是改变了这一行:
<xsl:apply-templates select="test[1]" mode="header"/>
,它做工精细。
谢谢SOOO发布这个。这是我的问题的答案 - 做一些非常相似的事情。本质上,我也需要将XML转换为CSV。我的输出比传统格式更符合你的要求(顶部没有INSERT语句)。 无论如何,mode =“header”技巧就是我所缺少的。 再一次,非常感谢你。 – tggagne