2016-02-12 97 views
2

我试图清理与看起来像任意元素名称的文件:递归空节点清理

<root> 
    <nodeone> 
     <subnode>with stuff</subnode> 
    </nodeone> 
    <nodeone> 
     <subnode>with other stuff</subnode> 
    </nodeone> 
    <nodeone> 
     <subnode /> 
    </nodeone> 
</root> 

成看起来像一个文件:

<root> 
    <nodeone> 
     <subnode>with stuff</subnode> 
    </nodeone> 
    <nodeone> 
     <subnode>with other stuff</subnode> 
    </nodeone> 
</root> 

你可以看到所有有空子女的“nodeone”消失了。我使用的解决方案删除了​​空的<subnode>,但保留<nodeone>。期望的结果是这两个元素都被删除。

我一个解决方案,当前的尝试(它恰恰没有)是:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="xml"/> 

    <xsl:template match="node()|@*"> 
     <xsl:call-template name="backwardsRecursion"> 
      <xsl:with-param name="elementlist" select="/*/node/*[normalize-space()]"/> 
     </xsl:call-template> 
    </xsl:template> 

    <xsl:template name="backwardsRecursion"> 
     <xsl:param name="elementlist"/> 

     <xsl:if test="$elementlist"> 
      <xsl:apply-templates select="$elementlist[last()]"/> 

      <xsl:call-template name="backwardsRecursion"> 
       <xsl:with-param name="elementlist" select="$elementlist[position() &lt; last()]"/> 
      </xsl:call-template> 
     </xsl:if> 
    </xsl:template> 

    <xsl:template match="/*/node/*[normalize-space()]"> 
      <xsl:value-of select="."/> 
    </xsl:template> 
</xsl:stylesheet> 

XSLT是不是我非常经常使用,所以我有点失落。

+1

这在我看来是一个很好问的问题。很显然,您已经试图找到一种递归调用模板的方式,就像您在其他编程语言中一样。然而,XSLT的美妙之处在于,它默认递归地应用模板,并且您编写的代码通常会停止或更改递归过程 - 正如下面的kjhughes所示。 –

回答

2

开始与身份转换,

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:template match="@*|node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
    </xsl:template> 
</xsl:stylesheet> 

,并添加一个模板来压制不signficant,非空间标准化的字符串值的元素,

<xsl:template match="*[not(normalize-space())]"/> 

,你会得到你所寻求的结果。

共有:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:template match="@*|node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
    </xsl:template> 

    <xsl:template match="*[not(normalize-space())]"/> 

</xsl:stylesheet>