I've been working on an XML to CSV transformation and I've been using the following XSLT doc for the transformation:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://ift.tt/tCZ8VR">
<xsl:output method="text"/>
<xsl:variable name="delimiter" select="','"/>
<xsl:key name="field" match="/*/*/*" use="local-name()"/>
<xsl:variable name="allFields" select="/*/*/*[generate-id()=generate-id(key('field', local-name())[1])]"/>
<xsl:template match="/">
<xsl:for-each select="$allFields">
<xsl:value-of select="local-name()"/>
<xsl:if test="position() < last()">
<xsl:value-of select="$delimiter"/>
</xsl:if>
</xsl:for-each>
<xsl:text/>
<xsl:apply-templates select="*/*"/>
</xsl:template>
<xsl:template match="*">
<xsl:variable name="this" select="."/>
<xsl:for-each select="$allFields">
<xsl:value-of select="$this/*[local-name() = local-name(current())]"/>
<xsl:if test="position() < last()">
<xsl:value-of select="$delimiter"/>
</xsl:if>
</xsl:for-each>
<xsl:text/>
</xsl:template>
</xsl:stylesheet>
If I run the transformation on the following xml:
<?xml version="1.0"?>
<Calls>
<Call xmlns="urn:eas-samples:en:xsd:phonecalls.1.0">
<CustomerID>000391</CustomerID>
<Filter1>1</Filter1> <Filter2>1</Filter2>
</Call>
<Call xmlns="urn:eas-samples:en:xsd:phonecalls.1.0">
<CustomerID>000528</CustomerID>
<Filter1>1</Filter1> <Filter2>1</Filter2>
</Call>
</Calls>
The transformation works fine and I get the following result:
CustomerID,Filter1,Filter2
000391,1,1
000528,1,1
However if I add an additional level to the children, for example:
<?xml version="1.0"?>
<Calls>
<Call xmlns="urn:eas-samples:en:xsd:phonecalls.1.0">
<CustomerID>000391</CustomerID>
<Filter1><AA>A</AA><BB>B</BB></Filter1>
</Call>
<Call xmlns="urn:eas-samples:en:xsd:phonecalls.1.0">
<CustomerID>000528</CustomerID>
<Filter1>1</Filter1> <Filter2>1</Filter2>
</Call>
</Calls>
I get the following output:
CustomerID,Filter1,Filter2
000391,AB,
000528,1,1
The problem occurs no matter how many levels I end up adding. What I want is for all the child names and the values to be presented in a CSV fashion.
Any idea what I am doing wrong?
Thanks!
No comments:
Post a Comment