0

I have XML which contains other XML as data in one of element.
I need to convert XML element data to CSV using XSLT.

This is my XML:

<?xml version="1.0" encoding="ISO-8859-1"?>
 <products>
   <details>
      <?xml version="1.0" encoding="ISO-8859-1"?>
       <catalog>
        <cd>
        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
        <company>Columbia</company>
        <price>10.90</price>
        <year>1985</year>
       </cd>
        <cd>
        <title>Hide your heart</title>
        <artist>Bonnie Tyler</artist>
        <country>UK</country>
        <company>CBS Records</company>
        <price>9.90</price>
        <year>1988</year>
      </cd>
      <cd>
        <title>Greatest Hits</title>
        <artist>Dolly Parton</artist>
        <country>USA</country>
        <company>RCA</company>
        <price>9.90</price>
        <year>1982</year>
        </cd>
    </catalog> 
   </details>
</products>

In this I need to convert data of <details> to CSV.

nempoBu4
  • 6,521
  • 8
  • 35
  • 40

1 Answers1

0

Assuming that each <cd> data represents a single data row in the csv file, try this out,

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xsl">
  <xsl:output method="text"/>
  <xsl:template match="/*">
    <xsl:for-each select="details/catalog/cd">
      <xsl:for-each select="*">
        <xsl:value-of select="."/>
        <xsl:variable name="countNode" select="count(../*)"/>
        <xsl:choose>
          <xsl:when test="position()=$countNode">
            <xsl:text>&#xa;</xsl:text>
          </xsl:when>
          <xsl:otherwise>,</xsl:otherwise>
        </xsl:choose>
      </xsl:for-each>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

This how the resultant data will look like

Empire Burlesque,Bob Dylan,USA,Columbia,10.90,1985
Hide your heart,Bonnie Tyler,UK,CBS Records,9.90,1988
Greatest Hits,Dolly Parton,USA,RCA,9.90,1982
Saurav
  • 592
  • 4
  • 21