【问题标题】: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>

【讨论】:

    【解决方案2】:

    您遇到的问题可能与以下事实有关:在 XML 中,不同形式的空白(换行符、空格等)被认为是等效的。看到这个答案:Is it "bad practice" to be sensitive to linebreaks in XML documents?

    【讨论】:

      【解决方案3】:

      您是否尝试过 &lt;xsl:output method="text"/&gt; tag 和/或将文字包含在 &lt;xsl:text&gt;...&lt;/xsl:text&gt; tags 中?

      如果您在 HTML 中呈现结果,问题是 HTML 不会在没有将输出包含在 tag like &lt;pre&gt; 中的情况下呈现换行符。输出一个 &lt;pre&gt; 标记,将您的文本输出包装在 XSLT 中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-06
        • 1970-01-01
        • 2014-12-06
        相关资源
        最近更新 更多