Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

People also ask

Can XSLT transform XML to CSV?

This post shows you how to convert a simple XML file to CSV using XSLT. The following XSL Style Sheet (compatible with XSLT 1.0) can be used to transform the XML into CSV. It is quite generic and can easily be configured to handle different xml elements by changing the list of fields defined ar the beginning.

How does XSLT transform XML?

The standard way to transform XML data into other formats is by Extensible Stylesheet Language Transformations (XSLT). You can use the built-in XSLTRANSFORM function to convert XML documents into HTML, plain text, or different XML schemas. XSLT uses stylesheets to convert XML into other data formats.


I'm trying to write an XSLT that will transform an XML document that I have to a CSV file. Here's a sample of the XML:

<?xml version="1.0" encoding="utf-8"?>
<Import>
    <Users>
        <User ID="user_1" EmailAddress="[email protected]">
            <Contact FirstName="John" LastName="Doe" />
            <Address Street1="808 Elm St" City="Anywhere" State="NY" />
        </User>

        <User ID="user_2" EmailAddress="[email protected]">
            <Contact FirstName="Jane" LastName="Noone" />
            <Address Street1="123 Some Rd" City="Anywhere" State="NY" />
        </User>     
    </Users>
</Import>

What I want is an XSLT that will output like so:

John,Doe,808 Elm St,Anywhere,NY
Jane,Noone,123 Some Rd,Anywhere,NY

I think I have the C# code correct to initiate the transform, but just in case I don't, here's that code as well:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Xsl;
using System.Configuration;

namespace UserTransform
{
    class Program
    {
        static void Main(string[] args)
        {
            string oldXML = ConfigurationSettings.AppSettings["XMLToBeTransformed"];
            string xsltLocation = ConfigurationSettings.AppSettings["XSLTfile"];
            string newCSV = ConfigurationSettings.AppSettings["NewCSVLocation"];

            XslCompiledTransform transform = new XslCompiledTransform();
            transform.Load(xsltLocation);
            transform.Transform(oldXML, newCSV);
        }
    }
}