需要删除不需要的空间元素

问题描述:

我想使用XSL删除不需要的空间元素。需要删除不需要的空间元素

XML我测试:

<Body> 
    <h1>abc</h1> 
    <h1>efg</h1> 
    <p>efgh</p> 
    <h1> </h1> 
</Body> 

XSL我使用:

<xsl:template match="Body"> 
    <xsl:copy> 
     <xsl:for-each-group select="*" group-adjacent="boolean(self::h1)"> 
     <xsl:choose> 
      <xsl:when test="current-grouping-key()"> 
       <h1> 
        <xsl:apply-templates select="current-group()/node()"/> 
       </h1> 
      </xsl:when> 
      <xsl:otherwise> 
       <xsl:apply-templates select="current-group()"/> 
      </xsl:otherwise> 
     </xsl:choose> 
     </xsl:for-each-group> 
    </xsl:copy> 
</xsl:template> 

输出我得到:

<Body> 
    <h1>abcefg</h1> 
    <p>efgh</p> 
    <h1> </h1> 
</Body> 

输出我想:

<Body> 
    <h1>abcefg</h1> 
    <p>efgh</p> 
</Body> 

我需要删除具有空间值的元素。请指教。在此先感谢

+0

我认为你需要更详细地解释你的输入可以看起来怎么样,并且导致你想要的,什么是应该,如果发生最后一个'h1'元素是否为空或仅填充空白,但包含一些数据?你想要一组新的'h1'元素吗? –

我假设,通过你写你的XSL文件的方式,你只希望合并h1元素。我进一步假设你只有希望删除“空白”h1元素。 (这是一个非常简单的修改,如果这些假设是不正确的)

考虑到这一点,这里是实现所需的输出的一种方式:

<xsl:strip-space elements="h1" /> 
<xsl:template match="Body"> 
    <xsl:copy> 
    <xsl:for-each-group select="*" group-adjacent="boolean(self::h1)"> 
     <xsl:choose> 
     <xsl:when test="current-grouping-key()"> 
      <xsl:if test="string-length(current-group()) > 0"> 
      <xsl:copy> 
       <xsl:apply-templates select="current-group()"/> 
      </xsl:copy> 
      </xsl:if> 
     </xsl:when> 
     <xsl:otherwise> 
      <xsl:for-each select="current-group()"> 
      <xsl:copy> 
       <xsl:apply-templates/> 
      </xsl:copy> 
      </xsl:for-each> 
     </xsl:otherwise> 
     </xsl:choose> 
    </xsl:for-each-group> 
    </xsl:copy> 
</xsl:template> 

具有扩展XML输入,以展示我的假设:

<Body> 
    <h1>abc</h1> 
    <h1>efg</h1> 
    <p>efgh</p> 
    <p>ijkl</p> 
    <h2>mnop</h2> 
    <h1> </h1> 
    <p> </p> 
</Body> 

输出为:

<Body> 
    <h1>abcefg</h1> 
    <p>efgh</p> 
    <p>ijkl</p> 
    <h2>mnop</h2> 
    <p> </p> 
</Body> 

的关键解决方案是将xsl:strip-space元素与string-length()函数结合在一起。这实际上导致每个h1元素都带有的任何数量,并且仅仅是空白区域被移除。

我还修复了第二个xsl:apply-templates元素的一个重大错误,这会导致每个连续的非h1元素序列被裸露在一起。 (您可以通过在设置current-group()节点的所有节点都需要循环来避免这种情况。)

+0

谢谢@robin。它的工作正常 – User501