代码之家  ›  专栏  ›  技术社区  ›  Guillaume

如何从文档中删除<b/>

  •  1
  • Guillaume  · 技术社区  · 16 年前

    我正在尝试使用XSLT复制大多数标记,但删除空标记” <b/> 标记。也就是说,它应该按原样复制 <b> </b> “或” <b>toto</b> “但完全删除” <

    我认为模板应该如下所示:

    <xsl:template match="b">
      <xsl:if test=".hasChildren()">
        <xsl:element name="b">
          <xsl:apply-templates/>
        </xsl:element>
      </xsl:if>
    </xsl:template>
    

    但是,当然,这个 hasChildren() “零件不存在……有什么想法吗?

    7 回复  |  直到 16 年前
        1
  •  3
  •   Community CDub    7 年前

    dsteinweg 让我走上正确的轨道。。。我最后做了:

    <xsl:template match="b">
        <xsl:if test="./* or ./text()">
            <xsl:element name="b">
                <xsl:apply-templates/>
            </xsl:element>
        </xsl:if>
    </xsl:template>
    
        2
  •  3
  •   Dimitre Novatchev    16 年前

    此转换忽略任何<b>没有任何节点子级的元素。本上下文中的节点指元素、文本、注释或处理指令节点。

    <xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output omit-xml-declaration="yes"/>
        <xsl:template match="node()|@*">
          <xsl:copy>
             <xsl:apply-templates select="node()|@*"/>
          </xsl:copy>
        </xsl:template>
    
        <xsl:template match="b[not(node()]"/>
    </xsl:stylesheet>

    注意,这里我们使用了最基本的XSLT设计模式之一——使用 identity transform 并为特定节点覆盖它。

    此技术功能非常强大,广泛用于此类任务,也可用于重命名、更改内容或属性、向任何可匹配的特定节点添加子节点或同级节点(除命名空间节点外的任何类型的节点均可用作<xsl:template/>的“匹配”属性中的匹配模式);

    希望这有帮助。

    干杯

    迪米特里·诺瓦切夫

        3
  •  2
  •   Darren Steinweg    16 年前

    我想知道这是否有效?

    <xsl:template match="b">
      <xsl:if test="b/text()">
        ...
    
        4
  •  1
  •   Vincent Ramdhanie    16 年前

    看看这是否有效。

    <xsl:template match="b">
      <xsl:if test=".!=''">
        <xsl:element name="b">
         <xsl:apply-templates/>
        </xsl:element>
      </xsl:if>
    </xsl:template>
    
        5
  •  1
  •   samjudson    16 年前

    另一种方法是执行以下操作:

    <xsl:template match="b[not(text())]" />
    
    <xsl:template match="b">
      <b>
        <xsl:apply-templates/>
      </b>
    </xsl:template>
    
        6
  •  1
  •   James Sulak    16 年前

    您可以将所有逻辑放在谓词中,并设置一个模板以仅匹配所需内容,然后将其删除:

    <xsl:template match="b[not(node())] />
    

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

    编辑: 现在使用node(),如下面的Dimitri。

        7
  •  0
  •   Tim C    16 年前

    xml:space=preserve 关于根元素

    <html xml:space="preserve">
    ...
    </html>
    

    这样,空间中的空间就空了<b></b>标记被保留,因此可以与<b/>在XSLT中。

    <xsl:template match="b">
       <xsl:if test="text() != ''">
       ....
       </xsl:if>
    </xsl:template>