代码之家  ›  专栏  ›  技术社区  ›  James Taylor

用xml元素包裹纯文本行

  •  0
  • James Taylor  · 技术社区  · 1 年前

    我有这个xml输入(它是一个正确的xml,我之前添加了根标记以使用xslt)。

    <root>
    Line 1
    Line 2
    Line 3</root>
    

    我需要这个输出。

    <root>
    <line>Line 1</line>
    <line>Line 2</line>
    <line>Line 3</line></root>
    

    我正在使用这个xslt,但只生成一行,其中包含所有三个值。

    <?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="xml" indent="yes"/<xsl:template match="root"><xsl:copy><xsl:apply-templates select="text()[normalize-space()]"/></xsl:copy></xsl:template><xsl:template match="text()"><line>
      <xsl:value-of select="normalize-space()"/></line></xsl:template></xsl:stylesheet>
    

    我如何解决这个问题以实现预期的输出?

    0 回复  |  直到 1 年前
        1
  •  0
  •   Martin Honnen    1 年前

    我从评论中提出的建议略有改进,并演变成一个完整的片段,可以在以下网址进行测试 this fiddle 例如。

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        exclude-result-prefixes="#all"
        version="3.0">
    
      <xsl:output indent="yes"/>
      
      <xsl:template match="root">
        <xsl:copy>
          <xsl:for-each select="tokenize(., '&#10;')[normalize-space()]"><line><xsl:value-of select="."/></line></xsl:for-each>
        </xsl:copy>
      </xsl:template>
      
    </xsl:stylesheet>
    

    和输出

    <root>
       <line>Line 1</line>
       <line>Line 2</line>
       <line>Line 3</line>
    </root>