2014-05-14 52 views
1

我正在使用以下XSLT從XML中刪除空節點。它通過刪除空節點正常工作,但它也添加了CRLF來代替刪除的節點。使用XSLT刪除XML的節點 - 不需要針對刪除的節點/字段的CRLF

<xsl:output omit-xml-declaration="yes" method="xml" version="1.0" /> 
    <xsl:template match="*[not(child::node())]"/> 
    <xsl:template match="@*|node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@* | node()"/> 
    </xsl:copy> 
    </xsl:template> 

Extra CRLFs

我不需要這些CRLFs。請建議!

+0

使用'的'和添加'縮進= 「是」''中的xsl:output' –

回答

1

這不是加入什麼,但它也不能去除遺留下來的原始的XML元素之間的空白文本節點。如果你的XML沒有混合內容,那麼最簡單的方法是刪除所有唯一的空白文本節點,然後重新縮進結果樹:如果您需要從原始的XML保存壓痕

<xsl:strip-space elements="*" /> 
<xsl:output omit-xml-declaration="yes" method="xml" version="1.0" indent="yes" /> 

那麼你需要稍微更多的創意

<xsl:template match="*[not(child::node())]"/> 
<xsl:template match="text()[not(normalize-space())] 
       [preceding-sibling::node()[1][self::*][not(child::node())]]" /> 

第二個模板將壓扁的空白,只有緊跟已壓扁第一模板元素的文本節點。

+0

它的工作原理!謝謝! –

1

它可能只是例如

<root> 
    <foo></foo> 
    <foo>2</foo> 
</root> 

導致

<root> 

    <foo>2</foo> 
</root> 

作爲代碼移除元件但不排除任何前述或尾部的空白文本節點。

在許多情況下,簡單地做

<xsl:output omit-xml-declaration="yes" method="xml" version="1.0" indent="yes"/> 
<xsl:strip-space elements="*"/> 

避免了這個問題,併爲您提供了很好的和一致的壓痕。

或者您需要編寫模板,以確保在刪除空白元素之前或之後的空白文本節點。

0

其他解決方案,我工作是通過使用翻譯。下面是XSLT:

<xsl:output omit-xml-declaration="yes" method="xml" version="1.0" /> 
    <xsl:template match="*[not(child::node())]"/> 
    <xsl:template match="@*|node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@* | node()"/> 
    </xsl:copy> 
    </xsl:template> 
    <xsl:template match="text()"> 
    <xsl:value-of select="translate(., '&#10;&#13;', '')"/> 
    </xsl:template>