I'd like to write an XSLT that will transform an XML document to a CSV file. Here's a sample of the XML:
<?xml version="1.0" encoding="utf-8"?>
<catalog>
<cd id="c1">
<singer id="s1">
<name>Kate</name>
<surname>Apple</surname>
</singer>
<title>Great CD</title>
</cd>
<cd id="c2">
<singer id="s2">
<name>Mary</name>
<surname>Orange</surname>
</singer>
<title>Even better CD</title>
</cd>
</catalog>
The resulting CSV file should be as follows:
singer, title
Kate Apple, Great CD
Mary Orange, Even better CD
I've come up with the following XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
singer,title
<xsl:for-each select="catalog/cd/singer">
<xsl:value-of select="concat(name,' ',surname,'
')" />
</xsl:for-each>
<xsl:for-each select="catalog/cd">
<xsl:value-of select="title"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
The resulting output is close to what I'd like to achieve:
singer,title
Kate Apple
Mary Orange
Great CDEven better CD
but the order of elements in incorrect. How do I fix this?
cdhas exactly one singer? If not, what should the result when there are two or none?