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

时间:2008-11-18 15:04:55

标签: xslt xpath

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

我认为模板看起来像:

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

但当然,“hasChildren()”部分不存在......有什么想法吗?

7 个答案:

答案 0 :(得分:3)

dsteinweg让我走上正轨...我最终做了:

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

答案 1 :(得分:3)

此转换会忽略任何&lt; b&gt;没有任何节点子元素的元素。此上下文中的节点表示元素,文本,注释或处理指令节点。

<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并覆盖特定节点。

将仅为名为“b”且没有(任何节点)子节点的节点选择覆盖模板。此模板为空(没有任何内容),因此其应用程序的效果是匹配节点被忽略/丢弃,并且不会在输出中重现。

这种技术非常强大,广泛用于此类任务,也用于重命名,更改内容或属性,将子项或兄弟项添加到任何可匹配的特定节点(除了名称空间节点外的每种类型的节点)可以在&lt; xsl:template /&gt;的“match”属性中用作匹配模式

希望这会有所帮助。

干杯,

Dimitre Novatchev

答案 2 :(得分:2)

我想知道这是否有用?

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

答案 3 :(得分:1)

看看这是否有效。

<xsl:template match="b">
  <xsl:if test=".!=''">
    <xsl:element name="b">
     <xsl:apply-templates/>
    </xsl:element>
  </xsl:if>
</xsl:template>

答案 4 :(得分:1)

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

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

<xsl:template match="b">
  <b>
    <xsl:apply-templates/>
  </b>
</xsl:template>

答案 5 :(得分:1)

您可以将所有逻辑放在谓词中,并设置模板以仅匹配您想要的内容并将其删除:

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

这假设您稍后在转换中有一个身份模板,听起来就像您一样。这会自动复制任何带有内容的“b”标签,这就是你想要的:

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

编辑现在使用下面的Dimitri之类的node()。

答案 6 :(得分:0)

如果您有权更新原始XML,可以尝试在根元素上使用 xml:space = preserve

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

这样,空的&lt; b&gt;中的空格。 &LT; / B个标签被保留,因此可以与&lt; b /&gt;区分开来。在XSLT中。

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