2013-06-06 259 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()!='']) ]"/> 

其中僅鎖定於帶有孩子的節點在輸入中,但不會有輸出中的子項。