Reputation: 107
Im trying to convert xml data to CSV. How do I add COMMA as data/text in CSV?
I couldn't use COMMA as separator since CSV is comma delimited file. Please help me to generate data as below:
rowId data
1 [xValue,yValue,zValue]
2 [xValue,yValue,zValue]
Some sample data:
<parent>
<c1>
<c2 x=1 y=2 z=3>
</c2>
</c1>
</parent>
My present xsl extracting the xml data is : Adding a COMMA as separator or text is delimiting the data in file. Please suggest the right way.
<xsl:for-each select="childlevel1/childlevel2">
<xsl:value-of select="concat('','[')"/>
<xsl:value-of select="@x"/>
<xsl:value-of select="@y"/>
<xsl:value-of select="@z"/>
<xsl:value-of select="concat(']','')"/>
</xsl:for-each>
Upvotes: 1
Views: 1712
Reputation: 70638
If your actual data has a comma in, which you don't want to treat as a delimiter, you need to put quote marks around that field.
Try this XSLT:
<xsl:template match="parent">
<xsl:text>rowId,data </xsl:text>
<xsl:for-each select="childlevel1/childlevel2">
<xsl:number />
<xsl:text>,</xsl:text>
<xsl:value-of select="concat('"[',@x,',',@y,',',@z,']"')"/>
<xsl:text> </xsl:text>
</xsl:for-each>
</xsl:template>
When you apply it to this XML
<parent>
<childlevel1>
<childlevel2 x="1" y="2" z="3" />
<childlevel2 x="11" y="12" z="13" />
</childlevel1>
</parent>
The following CSV is output
rowId,data
1,"[1,2,3]"
2,"[11,12,13]"
When you open this in your favourite Spreadsheet (like Microsoft Excel, or OpenOffice), it should only have two columns.
Upvotes: 2