0

有没有办法标准化元素文本的空间但保留可能存在的任何评论?

目前它过滤空间和评论?

提前致谢

4

1 回答 1

0

是的,你可以这样做:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:template match="@* | node()" priority="-1">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="text()">
    <xsl:value-of select="normalize-space()" />
  </xsl:template>
</xsl:stylesheet>

在此输入上运行时:

<root>
  <mynode>

    here is some    text <!-- That is some text -->

    and here    is some other text

    <!-- That was some other text -->
  </mynode>

  <!-- Here are some more comments -->
</root>

结果是:

<root><mynode>here is some text<!-- That is some text -->and here is some other text<!-- That was some other text --></mynode><!-- Here are some more comments --></root>

为了展示如何将其集成到实际执行某些操作的 XSLT 中:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:template match="@* | node()" priority="-1">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="text()">
    <xsl:value-of select="normalize-space()" />
  </xsl:template>

  <xsl:template match="/">
    <myNewRoot>
      <myNewNode>
        <xsl:apply-templates select="root/mynode/node()" />
      </myNewNode>
    </myNewRoot>
  </xsl:template>
</xsl:stylesheet>

当在上面的输入上运行时,结果是:

<myNewRoot>
  <myNewNode>here is some text<!-- That is some text -->and here is some other text<!-- That was some other text --></myNewNode>
</myNewRoot>
于 2013-04-15T10:10:34.080 回答