Java Collection<Properties> as XML: Convert to CSV

This xslt renders an XML file of a java Collection instance, containing java.lang.Properties instances as csv, one row per Properties instance.

Create the xml file like so:

...
		Collection canoes = new HashSet();
		
		canoes.add(canoeProps1);
		canoes.add(canoeProps2);
		...
		FileOutputStream fstream = new FileOutputStream("collectedproperties.xml");

		try {
		   XMLEncoder ostream = new XMLEncoder(fstream);

		   try {
		      ostream.writeObject(canoes);
		      ostream.flush();
		   } finally {
		      ostream.close();
		   }
		} finally {
		   fstream.close();
		}
...

Copy the xslt below to a file (suggest you copy paste as formatting may hide one of the long lines in wordpress standard view). Throw it and your collectedproperties.xml at your xsl processor to get a rudimentary csv file.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

	<!-- 
	a trivial xml to csv xslt for a Collection of Properties written  
	as XML by java.beans.XMLEncoder                                  
	-->
	<!-- mccalni, 18-dec-09 -->

	<xsl:output method="text" encoding="iso-8859-1"/>

	<xsl:template match="java/object/void" >
		<xsl:apply-templates select="object"/>
	</xsl:template>

	<xsl:template match="object">
		<xsl:apply-templates select="void"/><xsl:text>&#xD;</xsl:text>
	</xsl:template>

	<xsl:template match="void">
		<xsl:for-each select="*">"<xsl:value-of select="normalize-space(.)"/>",</xsl:for-each>  
	</xsl:template>

</xsl:stylesheet>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s