我需要使用XSL從XML生成簡單的純文本輸出。由於我沒有在網上找到任何好的,簡明的例子,我決定在這裏發佈我的解決方案。任何涉及到一個更好的例子鏈接當然會意識到:這有助於我在這裏使用xsl輸出純文本
<?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:輸出省略標準的聲明開頭的輸出文件
- 使用xml:space =「preserve」屬性來保留我在xsl:for-each標記內寫入的任何空格。這也要求我在for-each標籤中寫入所有的代碼,包括標籤以及單行(除了換行符)。
- 使用插入換行符 - 再次我不得不在這裏省略標準xml縮進。
所得並且爲此XSLT期望的輸出是:
在-f ALLUSER 23時58 2010年4月17日
在-f ggroup67 19:58 2010年4月28日
在-f ggroup70 15: 58 2010年4月18日
在-f ALLUSER 23:58 2010年4月18日
在-f ggroup61 7:58 2010年9月22日
在-f ggroup60 23:58 2010年9月21日
在-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>
您可以使用'concat('at -f',username,'',startTime/@ hours,'',...)'節省''元素的數量。此外,你可以打包你的源代碼 - 如果你在代碼中這樣做,它不會影響輸出。 –
2011-05-06 08:50:44
好問題,+1。看到我的答案是一個完整的,非常簡短的,真正通用的解決方案 – 2011-05-06 13:25:12
@Christopher Creutzig:感謝concat()的精彩建議。你指的是「包裝你的源代碼」? – Chris 2011-05-08 16:30:47