Home > Net >  Converting XML to CSV using XSLT Formatting Issue
Converting XML to CSV using XSLT Formatting Issue

Time:11-29

I have the following XML

<Data>
    <Employee>
        <Name>
            <FirstName>John</FirstName>
            <LastName>Snow</LastName>
        </Name>
        <DOB>1990-01-01</DOB>
        <Passport>
            <Country>United Kingdom</Country>
            <ID>12345678</ID>
        </Passport>
        <Passport>
            <Country>United States of America</Country>
            <ID>789101112</ID>
        </Passport>
    </Employee>
</Data>

And I am converting it as seen below:

<xsl:for-each select="Data/Employee">            
            <xsl:value-of select="Name/FirstName"/>
            <xsl:text>,</xsl:text>
            <xsl:value-of select="Name/LastName"/>
            <xsl:text>,</xsl:text>
            <xsl:for-each select="Passport">
                <xsl:value-of select="Country"/>
                <xsl:text>,</xsl:text>
                <xsl:value-of select="ID"/>                
                <xsl:text>&#xd;</xsl:text>
            </xsl:for-each>
            <xsl:text>,</xsl:text>
            <xsl:value-of select="DOB"/>
        </xsl:for-each>    

The output I am getting is:

John,Snow,United Kingdom,12345678
United States of America,789101112
,1990-01-01

But I require the passport information to be populated below each other and then DOB to be shown on the top line as seen below:

John,Snow,United Kingdom,12345678,1990-01-01
,,United States of America,789101112

Any help would be appreciated

CodePudding user response:

Perhaps like this:

XSLT 2.0

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="text" encoding="UTF-8"/>

<xsl:template match="/Data">
    <xsl:for-each select="Employee">
        <xsl:for-each select="Passport">
            <xsl:choose>
                <xsl:when test="position()=1">
                    <xsl:value-of select="../Name/(FirstName, LastName), Country,ID, ../DOB" separator=","/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="'', '', Country,ID, ''" separator=","/>
                </xsl:otherwise>
            </xsl:choose>
            <xsl:text>&#10;</xsl:text>
        </xsl:for-each>
    </xsl:for-each>
</xsl:template>
  
</xsl:stylesheet>

Note that I have added a trailing comma in the place of the "missing" DOB.

  • Related