I needed to use XSL to generate simple plain text output from XML. Since I didn't find any good, concise example online, I decided to post my solution here. Any links referring to a better example would of course be appreciated:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" > <xsl:output method="text" omit-xml-declaration="yes" indent="no"/> <xsl:template match="/"> <xsl:for-each select="script/command" xml:space="preserve">at -f <xsl:value-of select="username"/> <xsl:value-of select="startTime/@hours"/>:<xsl:value-of select="startTime/@minutes"/> <xsl:value-of select="startDate"/><xsl:text> </xsl:text></xsl:for-each> </xsl:template> </xsl:stylesheet>
A few important things that helped me out here:
The resulting and desired output for this xslt was:
at -f alluser 23:58 17.4.2010
at -f ggroup67 7:58 28.4.2010
at -f ggroup70 15:58 18.4.2010
at -f alluser 23:58 18.4.2010
at -f ggroup61 7:58 22.9.2010
at -f ggroup60 23:58 21.9.2010
at -f alluser 3:58 22.9.2010
As I said, any suggestions of how to do this more elegantly would be appreciated.
FOLLOW-UP 2011-05-08:
Here's the type of xml I am treating:
<script xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="script.xsd"> <command> <username>alluser</username> <startTime minutes="58" hours="23"/> <startDate>17.4.2010</startDate> </command> </script>
XSLT uses the <xsl:output> element to determine whether the output produced by the transformation is conformant XML (<xsl:output method="xml"/> ), valid HTML (<xsl:output method="html"/> ), or unverified text (< xsl:output method="text"/> ).
XSLT <xsl:text>The <xsl:text> element is used to write literal text to the output. Tip: This element may contain literal text, entity references, and #PCDATA.
The <xsl:text> element writes literal text to the output tree.
script/command
and eliminate the xsl:for-each
concat()
can be used to shorten the expression and save you from explicitly inserting so many <xsl:text>
and <xsl:value-of>
elements.

for the carriage return, rather than relying on preserving the line-break between your <xsl:text>
element is a bit more safe, since code formatting won't mess up your line breaks. Also, for me, it reads as an explicit line-break and is easier to understand the intent.<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" > <xsl:output method="text" omit-xml-declaration="yes" indent="no"/> <xsl:template match="script/command"> <xsl:value-of select="concat('at -f ' ,username ,' ' ,startTime/@hours ,':' ,startTime/@minutes ,' ' ,startDate ,'
')"/> </xsl:template> </xsl:stylesheet>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With