【问题标题】:XSLT - output to html a specific XML element which contains formatted text - output should be sameXSLT - 输出到 html 包含格式化文本的特定 XML 元素 - 输出应该相同
【发布时间】:2011-10-10 12:45:26
【问题描述】:
我有一个包含格式化文本数据的 xml 元素:
<MESSAGE>
<TranslationReport>
Translation Report
==================
Contains errors ? true
Contains warnings ? false
There are 9 entries in the report
我希望我的 xslt(输出到 html)的结果与 TranslationReport 的内容完全匹配。
我所做的一切都只需要一个数据(全部在一行中 - 见下文)。这看起来很简单,但我已经在我的所有书籍和其他任何地方搜索过......
翻译报告 ================== 包含错误?真 包含
警告? false 报告中有 9 个条目
【问题讨论】:
标签:
html
xml
xslt
transformation
【解决方案1】:
如果你要渲染成 html,你有两个选择:
- 使用
pre标签在浏览器中呈现您的文本。
- 使用一些高级 XPath 2.0 函数解析您的文本,并根据需要处理每个文本行。
这里是第一个选项愚蠢的例子:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="MESSAGE/TranslationReport">
<html>
<body>
<pre>
<xsl:value-of select="."/>
</pre>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
在第二个选项中,我们将使用 XPath 2.0 函数 tokenize 解析您的文本,拆分所有行并用 eanted 标记包裹每一行。
这是一个愚蠢的例子:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="MESSAGE/TranslationReport">
<html>
<body>
<xsl:for-each select="tokenize(.,'\n')
[not(position()=(1,last()))]">
<p class="TranslationReport">
<xsl:value-of select=".[position()]"/>
</p>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
在第二种情况下,输出将是:
<html>
<body>
<p class="TranslationReport">Translation Report</p>
<p class="TranslationReport">==================</p>
<p class="TranslationReport">Contains errors ? true</p>
<p class="TranslationReport">Contains warnings ? false</p>
<p class="TranslationReport">There are 9 entries in the report</p>
</body>
</html>
【解决方案3】:
您是否尝试过 <xsl:output method="text"/> tag 和/或将文字包含在 <xsl:text>...</xsl:text> tags 中?
如果您在 HTML 中呈现结果,问题是 HTML 不会在没有将输出包含在 tag like <pre> 中的情况下呈现换行符。输出一个 <pre> 标记,将您的文本输出包装在 XSLT 中。