I have a simple xml file:
<headlines>
<headline>
...
</headline>
<headline>
...
</headline>
<headline>
...
</headline>
</headlines>
All I want to do is shuffle the order in which headlines appear. I've been fooling around how this template should look, but I can't get it working.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/headline">
<xsl:for-each select="headline">
__not sure what to do here? rand() isn't a thing?__
One way to do this would be to use the function generate-id() as a sorting criterion. Suppose you have the following input:
<?xml version="1.0" encoding="ISO-8859-1"?>
<headlines>
<headline>
Limburg
</headline>
<headline>
Fukushima
</headline>
<headline>
Große Koalition
</headline>
<headline>
Flugzeugabsturz
</headline>
</headlines>
With this XSLT you can "randomize" the output:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="ISO-8859-1"/>
<xsl:template match="/headlines">
<headlines>
<xsl:for-each select="headline">
<xsl:sort select="generate-id(.)"/>
<headline id="{generate-id(.)}">
<xsl:copy-of select="./text()"/>
</headline>
</xsl:for-each>
</headlines>
</xsl:template>
</xsl:stylesheet>
The result is
<?xml version="1.0" encoding="ISO-8859-1"?>
<headlines><headline id="idm3928">
Limburg
</headline><headline id="idm5512">
Flugzeugabsturz
</headline><headline id="idm5704">
Große Koalition
</headline><headline id="idm5920">
Fukushima
</headline></headlines>
Three things should be noted:
- The output of attribute "id" in the headline tag is not necessary. This is just for visualizing the sort criterion.
- The sorting order depends on the xslt processor used (in this case a Debian xsltproc).
- It's not really "random". However, the processor xsltproc actually chooses new ids with every call so in fact the headlines get "shuffled". :-)