使用XSLT将xml转换为CSV [英] Converting xml to CSV using XSLT

查看:88
本文介绍了使用XSLT将xml转换为CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是XSLT的新手,并且经历了SO上的一些较早的主题 遵循的主题

i am new to XSLT and have gone through some of the earlier thread on SO Thread i Followed

我的要求类似,我需要将XML转换为CSV,例如我有以下XML

my requirements are similar and i need to convert XML to CSV, for e.g i have following XML

<?xml version="1.0" encoding="UTF-8"?>
<impex>
<record>
<Employee/>
<UID>aa</UID>
<Name>HR Manager</Name>
<Groups/>
<Password>123456</Password>
</record>
<record>
<Employee/>
<UID>bb</UID>
<Name>HR Executive</Name>
<Groups/>
<Password>123456</Password>
</record>
</impex>

并且我需要将此XML转换为以下csv输出

and i need to convert this XML to following csv output

INSERT_UPDATE Employee;UID[unique=true];name;groups(uid);password
;"aa";"HR Manager";;"123456"
 ;"bb";"HR Executive";;"123456"

我必须动态管理csv标头(基于xml元素)

where i have to manage csv headers dynamically (based on xml elements)

另外,如果某些值丢失,我还必须注意,我可以提供它们 例如 丢失或为空,在这种情况下,我需要为生成的csv提供一些默认值,因为此csv将是最终输出,将导入到系统中

additonaly i have also to take care if some of the values are missing i can provide them e.g is missing or its empty in such case i need to provide some default value to the generated csv as this csv will be the final output which will be imported to the system

任何可以帮助我前进的起步帮助将不胜感激

any starting help by which i can move ahead will be much appreciated

推荐答案

不是最漂亮的,但是可以使用

Not the most beautiful, but it works

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="text" />

<xsl:template match="/impex">
    <xsl:text>INSERT_UPDATE </xsl:text>
    <xsl:apply-templates select="record[1]/*" mode="header"/>
    <xsl:apply-templates select="record" />
</xsl:template>


<xsl:template match="*" mode="header" >
    <xsl:value-of select="name()"/>
    <xsl:choose>
        <xsl:when test="position()=last()">
            <xsl:text>&#10;</xsl:text>
        </xsl:when>
        <xsl:otherwise>;</xsl:otherwise>
    </xsl:choose>
</xsl:template>

<xsl:template match="record">
    <xsl:apply-templates select="*"/>
</xsl:template>

<xsl:template match="*" >
    <xsl:value-of select="."/>
    <xsl:choose>
        <xsl:when test="position()=last()">
            <xsl:text>&#10;</xsl:text>
        </xsl:when>
        <xsl:otherwise>;</xsl:otherwise>
    </xsl:choose>
</xsl:template>
</xsl:stylesheet>

这篇关于使用XSLT将xml转换为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆