首页 文章

我如何理解XSLT中的换行符?

提问于
浏览
1

我有一段看起来像这样的XML:

<bunch of other things>
<bunch of other things>
<errorLog> error1 \n error2 \n error3 </errorLog>

我想修改此XML运行的XSLT,以便在 errors1error3 之后应用换行符 .

我可以完全控制errorLog的输出或XSLT文件的内容,但我不知道如何制作XML或XSLT以使输出HTML显示换行符 . 是否更容易将XML输出更改为将导致换行的某个特殊字符,还是修改XSLT以将 \n 解释为换行符?

有一个example on this site包含类似于我想要的东西,但我的 <errorLog> XSLT嵌套在另一个模板中,我不确定模板中的模板是如何工作的 .

2 回答

  • 3

    反斜杠用作许多语言(包括C和Java)中的转义字符,但不用于XML或XSLT . 如果你将\ n放在样式表中,那么's not a newline, it'的两个字符反斜杠后跟"n" . 编写换行符的XML方式是 &#xa; . 但是,如果您以HTML格式向浏览器发送换行符,则会将其显示为空格 . 如果您想要浏览器显示换行符,则需要发送
    元素 .

  • 2

    如果您可以控制 errorLog 元素,那么您也可以使用文字LF字符 . 就XSLT而言,它与任何其他角色没有什么不同 .

    至于创建使用换行符显示的HTML,您将需要添加
    元素来代替XML源中的任何标记 . 如果您可以将每个错误放在一个单独的元素中,这将是最简单的

    <errorLog>
      <error>error1</error>
      <error>error2</error>
      <error>error3</error>
    </errorLog>
    

    然后XSLT不必经历分裂文本本身的相当笨拙的过程 .

    从您的问题中获取此XML数据

    <document>
      <bunch-of-other-things/>
      <bunch-of-other-things/>
      <errorLog>error1 \n error2 \n error3</errorLog>
    </document>
    

    这个样式表

    <?xml version="1.0" encoding="utf-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
      <xsl:strip-space elements="*"/>
      <xsl:output method="xml" indent="yes" omit-xml-declaration="yes" />
    
      <xsl:template match="/document">
        <html>
          <head>
            <title>Error Log</title>
          </head>
          <body>
            <xsl:apply-templates select="*"/>
          </body>
        </html>
      </xsl:template>
    
      <xsl:template match="node()|@*">
        <xsl:copy>
          <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
      </xsl:template>
    
      <xsl:template match="errorLog">
        <p>
          <xsl:call-template name="split-on-newline">
            <xsl:with-param name="string" select="."/>
          </xsl:call-template>
        </p>
      </xsl:template>
    
      <xsl:template name="split-on-newline">
        <xsl:param name="string"/>
        <xsl:choose>
          <xsl:when test="contains($string, '\n')">
            <xsl:value-of select="substring-before($string, '\n')"/>
            
    <xsl:call-template name="split-on-newline"> <xsl:with-param name="string" select="substring-after($string, '\n')"/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select="$string"/>
    </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet>

    会产生这个输出

    <html>
       <head>
          <title>Error Log</title>
       </head>
       <body>
          <bunch-of-other-things/>
          <bunch-of-other-things/>
          <p>error1 
    error2
    error3
    </p> </body> </html>

相关问题