2013-06-06 253 views
0

我想从源XML中删除空节点。删除空节点已成功。但我也尝试删除包含空的子节点的所有节点。删除空节点和空子节点

源XML:

<?xml version="1.0" encoding="UTF-8"?> 
<data> 
    <element> 
     <a></a> 
     <b>sde</b> 
     <c fixedAttr="fixedValue"> 
      <d>ert</d> 
      <e></e> 
     </c> 
     <f fixedAttr="fixedValue"> 
      <g></g> 
      <h></h> 
      <i></i> 
     </f> 
    </element> 
</data> 

当前XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output omit-xml-declaration="yes" method="xml" encoding="UTF-8" indent="yes"/> 
    <xsl:strip-space elements="*"/> 

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

    <xsl:template match="*[not(@*|*|comment()|processing-instruction()) and normalize-space()='']"/> 
</xsl:stylesheet> 

当前的结果:

<?xml version="1.0" encoding="UTF-8"?> 
<data> 
    <element> 
     <b>sde</b> 
     <c fixedAttr="fixedValue"> 
      <d>ert</d> 
     </c> 
     <f fixedAttr="fixedValue"/> 
    </element> 
</data> 

通缉的结果:

<?xml version="1.0" encoding="UTF-8"?> 
<data> 
    <element> 
     <b>sde</b> 
     <c fixedAttr="fixedValue"> 
      <d>ert</d> 
     </c> 
    </element> 
</data> 

空的父节点<f fixedAttr="fixedValue"/>也需要移除。

+0

这是不完全清楚什么是考虑作为**空**。你的xslt看起来像是空的,如果没有文本,子项,属性等等。但是你的节点f有一个属性,应该被认为是空的任何方式? –

+0

的确可以忽略属性。如果子元素不包含文本,则父元素被认为是空的。 –

回答

2

我还没有测试过它,但以下xslt似乎正在工作。

<xsl:template match="node()|@*"> 
    <xsl:if test="normalize-space(string(.)) != ''"> 
     <xsl:copy> 
      <xsl:apply-templates select="node()|@*"/> 
     </xsl:copy> 
    </xsl:if> 
</xsl:template> 

编辑: 如果你想保留空属性可能与此

<xsl:template match="node()[normalize-space(string(.)) != '']|@*"> 
     <xsl:copy> 
      <xsl:apply-templates select="node()|@*"/> 
     </xsl:copy> 
</xsl:template> 

完成
2

要通过模板拆除对它们会被忽略节点的父(视为空)节点:

<xsl:template match="*[not(@*|* |comment()|processing-instruction()) and normalize-space()='']"/> 

添加一个新的模板:

<xsl:template match="*[ * and not(*[ @* or * or comment() or processing-instruction() or normalize-space()!='']) ]"/> 

其中仅锁定于带有孩子的节点在输入中,但不会有输出中的子项。