我需要使用 XSL 从 XML 生成简单的纯文本输出。由于我没有在网上找到任何好的、简洁的示例,我决定在这里发布我的解决方案。当然,任何引用更好示例的链接都会受到赞赏:
<?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>
一些对我有帮助的重要事情:
- 使用 xsl:output 省略输出文档开头的标准声明
- 使用 xml:space="preserve" 属性来保留我在 xsl:for-each 标记中编写的任何空格。这还要求我将所有代码都写在 for-each 标记中,包括该标记在内,都写在一行上(换行符除外)。
- 使用 插入换行符 - 我不得不在这里省略标准 xml 缩进。
此 xslt 的结果和所需输出是:
在 -f alluser 23:58 17.4.2010
在 -f ggroup67 7:58 28.4.2010
在 -f ggroup70 15:58 18.4.2010
在 -f alluser 23:58 18.4.2010
在 -f ggroup61 7:58 22.9.2010
在-f ggroup60 23:58 21.9.2010
在-f alluser 3:58 22.9.2010
正如我所说,任何关于如何更优雅地做到这一点的建议都将不胜感激。
跟进 2011-05-08:
这是我正在处理的 xml 类型:
<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>