开发者

Converting xml to CSV using XSLT

开发者 https://www.devze.com 2023-03-28 15:48 出处:网络
i am new to XSLT and have gone through some of the earlier thread on SO Thread i Followed my requirements are similar and i need to convert XML to CSV, for e.g i have following XML

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

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>

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"

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

additonaly i have also to take care if some of the values are missing i can provide them e.g 开发者_StackOverflow社区 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>
0

精彩评论

暂无评论...
验证码 换一张
取 消