Assuming I have the following XML and I care only about the FruitId, and the customer Numbereaten, and Weight attributes.
<AllFruits xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- All fruits below. -->
<Fruit>
<FruitId>Bannana</FruitId>
<FruitColor>Yellow</FruitColor>
<FruitShape>Moon</FruitShape>
<Customer>
<Name>Joe</Name>
<Numbereaten>5</NumberEaten>
<Weight>2.6</Weight>
</Customer>
<Customer>
<Name>Mark</Name>
<Numbereaten>8</NumberEaten>
<Weight>5.0</Weight>
</Customer>
</Fruit>
<Fruit>
<FruitId>Apple</FruitId>
<FruitColor>Red</FruitColor>
<FruitShape>Circle</FruitShape>
<Customer>
<Name>Joe</Name>
<Numbereaten>2</NumberEaten>
<Weight>1.5</Weight>
</Customer>
</Fruit>
<Fruit>
<FruitId>Pear</FruitId>
<FruitColor>Green</FruitColor>
<FruitShape>Oval</FruitShape>
<Customer>
<Name>Mark</Name>
<NumberEaten>1</NumberEaten>
<Weight>6</Weight>
</Customer>
<Customer>
<Name>Josh</Name>
<NumberEaten>9</NumberEaten>
<Weight>10</Weight>
</Customer>
<Customer>
<Name>Willis</Name>
<NumberEaten>2</NumberEaten>
<Weight>5.6</Weight>
</Customer>
</Fruit>
</AllFruits>
What is the proper XSLT for the above? I tried the following, but it did not work.
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="text" encoding="ISO-8859-1" />
<xsl:variable name="newline" select="'
'"/>
<xsl:template match="Fruit">
<xsl:for-each select="Customer">
<xsl:value-of select="preceding-sibling::FruitId" />
<xsl:text>,</xsl:text>
<xsl:value-of select="Numbereaten" />
<xsl:text>,</xsl:text>
<xsl:value-of select="Weight" />
<xsl:value-of select="$newline" />
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
To attempt to test the XSLT, I use the following Java code:
Source xmlSource = new StreamSource(new File("xmlFile"));
Source xsltSource = new StreamSource(new File("xsltFile"));
Transformer transformer = TransformerFactory.newInstance().newTransformer(xsltSource);
transformer.transform(xmlSource, new StreamResult(System.out));
All that I am getting is the XML being output into the console... not in the format I would desire like:
Bannana, 5, 2.6
Bannana, 8, 5
...
Apple 6, 5
Apple 3, 2
If what I am trying to do does not work, if there are other better approaches other than XSLT let me know. It feels like something like this should be simple.
Where is your
xslStream
being used ?Do this:
If you want to get rid of the empty lines just add in your XSLT file after line
this line
You're actually doing a
copy
transformation i.e. no stylesheet transformations are being applied. This is the reason why you're simply seeing the contents of your source XML file as the output on your console.To apply the stylesheet you need to set it while getting an instance of your
Transformer
XSLT Output: