1

使用 XSLT,我如何评论单个节点而不评论其子节点?

我有这个html:

<html>
  <body>
    <div class="blah" style="blahblah">
      <span>
        <p>test</p>
      </span>
    </div>
  </body>
</html>

我想要这个输出:

<html>
  <body>
    <!-- div class="blah" style="blahblah" -->
      <span>
        <p>test</p>
      </span>
    <!-- /div -->
  </body>
</html>

复制子节点并复制注释节点的任何属性是关键。

以下是我最好的尝试,但不起作用。XSLT 处理器喊道:“在添加了文本、注释、pi 或子元素节点后,不能将属性和命名空间节点添加到父元素。”

<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

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

    <xsl:template match="div">
      <xsl:text disable-output-escaping="yes">&lt;!--</xsl:text>
      <xsl:copy>
        <xsl:text disable-output-escaping="yes">--&gt;</xsl:text>
          <xsl:apply-templates select="@* | node()"/>
        <xsl:text disable-output-escaping="yes">&lt;!--</xsl:text>
      </xsl:copy>
      <xsl:text disable-output-escaping="yes">--&gt;</xsl:text>
    </xsl:template>

</xsl:stylesheet>
4

2 回答 2

1

值得指出的是,您可以只使用<xsl:comment>在输出 XML 中创建注释,而不必担心正确关闭它们。如果未正确输入结束注释分隔符,您所做的很容易导致问题。

这可以解决问题:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

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

    <xsl:template match="div">
      <xsl:comment>
          <xsl:text> div </xsl:text>
          <xsl:for-each select="@*">
               <xsl:value-of select="local-name()"/>
               <xsl:text>="</xsl:text>
               <xsl:value-of select="."/>
               <xsl:text>" </xsl:text>
           </xsl:for-each>
      </xsl:comment>
      <xsl:apply-templates select="./*" />
      <xsl:comment> /div </xsl:comment>
    </xsl:template>

</xsl:stylesheet>

当输出打印得很漂亮时,它会给出:

<html>
   <body>
      <!-- div class="blah" style="blahblah" -->
      <span>
         <p>test</p>
      </span>
      <!-- /div -->
   </body>
</html>
于 2013-07-12T04:59:18.037 回答
0

这是对 XSLT 的一种非常可怕的使用,但这似乎可行,而且我想不出更清洁的方法:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

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

  <xsl:template match="div">
    <xsl:text disable-output-escaping="yes">&lt;!--</xsl:text>
    <xsl:copy>
      <xsl:apply-templates select="@*"/>
      <xsl:text disable-output-escaping="yes">--&gt;</xsl:text>
      <xsl:apply-templates select="node()"/>
      <xsl:text disable-output-escaping="yes">&lt;!--</xsl:text>
    </xsl:copy>
    <xsl:text disable-output-escaping="yes">--&gt;</xsl:text>
  </xsl:template>

</xsl:stylesheet>
于 2013-07-12T04:58:36.480 回答