2016-02-15 68 views
1

我試圖清理與看起來像任意元素名稱的文件:XSLT - 遞歸空節點清理

<root> 
    <nodeone> 
     <subnode blah="1" blah2="abc" /> 
    </nodeone> 
    <nodeone> 
     <subnode>with other stuff</subnode> 
    </nodeone> 
    <nodeone> 
     <subnode /> 
    </nodeone> 
</root> 

成看起來像一個文件:

<root> 
    <nodeone> 
     <subnode blah="1" blah2="abc" /> 
    </nodeone> 
    <nodeone> 
     <subnode>with other stuff</subnode> 
    </nodeone> 
</root> 

你可以看到所有具有空子項的「nodeone」都消失了,但保留了具有內容或非空屬性的任何<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:copy> 
      <xsl:apply-templates select="@*|node()"/> 
     </xsl:copy> 
    </xsl:template> 

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

</xsl:stylesheet> 

這消除與空白的內容物的任何節點,並保留的屬性,而且還除去來自輸出,這是不期望的結果的<nodeone />文本。

回答

2

,那就試試這個模板

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

這裏.//@*會檢查當前元素的屬性(被匹配)以及所有子元素了。

0

您正在匹配任何名稱既沒有文本內容也沒有屬性的元素。所以這也匹配你的<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" indent="yes"/> 
    <xsl:template match="@*|node()"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
     </xsl:copy> 
    </xsl:template> 
    <xsl:template match="nodeone[*[not(normalize-space())][not(@*)]]"/> 
</xsl:stylesheet> 
+0

順便說一句,如果你想要無子節點'nodeone'元素(即'')也被移除,那麼使用''而不是。 –

+0

正如我剛纔所說的,這是一個包含任意節點的文檔。我不一定知道他們叫什麼,但如果他們是空的,沒有內容屬性,我希望他們從輸出中省略。點是,我不能創建一個像你提供的選擇特定節點的結構。那有意義嗎? – TRAL

+0

因此''的名字總是nodeone,但是''可能有不同的名字?我改變了我的回答以反映這一點。 –