How do I write an XSLT to transform XML to CSV? How do I write an XSLT to transform XML to CSV? xml xml

How do I write an XSLT to transform XML to CSV?


Create a template that matches all users, then pull out the information you need in the order you want:

<xsl:template match="//User">  <xsl:value-of select="Contact/@FirstName"/>,  <xsl:value-of select="Contact/@LastName"/>,  <!--etc--></xsl:template>

Obviously you'll need to make sure whitespace is handled the way you want it to be, with newlines in the right places. I'll leave this as an exercise to the reader.


I always prefer to let the browser process the XML relieving the server to carry on with more demanding job. That said, here's a sample XSLT that should translate your XML and present it in a CSV format as shown above.

Hope this sample code helps, if not, let me know.

<xsl:stylesheet version="1.0">    <xsl:template match="/">        <table>            <xsl:for-each select="//User">                <tr>                    <td>                        <xsl:value-of select="conat('[', @ID, ']')"/>                        <xsl:value-of select="','"/>                        <xsl:value-of select="Contact/@FirstName"/>                        <xsl:value-of select="','"/>                        <xsl:value-of select="Contact/@LastName"/>                        <xsl:value-of select="','"/>                        <xsl:value-of select="Address/@Street1"/>                        <xsl:value-of select="','"/>                        <xsl:value-of select="Address/@City"/>                        <xsl:value-of select="','"/>                        <xsl:value-of select="Address/@State"/>                    </td>                </tr>             </xsl:for-each>        </table>     </xsl:template></xsl:stylesheet>


In my experience I've always used XSLT on the client side of things not server side which is what you seem to be attempting with C#