2010-12-10 59 views
7

我不是XSLT嚮導。XSLT刪除空的節點和節點-1

我有我使用刪除空節點當前的XSLT:

string strippingStylesheet = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">" + 
       "<xsl:template match=\"@*|node()\">" + 
       "<xsl:if test=\". != ''\">" + 
       "<xsl:copy>" + 
       "<xsl:apply-templates select=\"@*|node()\"/>" + 
       "</xsl:copy>" + 
       "</xsl:if></xsl:template></xsl:stylesheet>"; 

我需要找到一種方法,也與他們-1刪除節點。以前的開發人員認爲將系統中的每個int都默認爲-1是個好主意,而且這意味着所有DB字段都有-1,而不是null。因此,儘管我想擊敗死馬(用棍子,蝙蝠,火箭筒),但我需要回去工作並完成這一工作。

任何幫助將是偉大的。

+0

好問題,+1。請參閱我的答案,瞭解「空節點」的適當定義以及完整但非常短的解決方案。 :) – 2010-12-10 02:41:35

+2

另一種解決方法是簡單地改變你的行`「」`to`「」`。 – LarsH 2010-12-10 07:05:14

回答

12

我目前的XSLT我」 m使用至 刪除空節點:

。 。 。 。 。 。 。 。 。

我需要找到一種方法,也刪除它們

與-1 節點我猜想,這需要除去所有「空節點」。

處理取決於「空節點」的定義。在你的情況下,一個合理的定義是:任何元素沒有屬性和子元素或沒有屬性,並且只有一個子元素是文本節點,其值爲-1

對於這個定義這裏是一個簡單的解決方案。

這種轉變

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" 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(@*) and not(*) and (not(text()) or .=-1)]"/> 
</xsl:stylesheet> 

當此示例XML文檔施加:

<t> 
<a>-1</a> 
<a>2</a> 
<b><c/></b> 
<d>-1</d> 
<d>15</d> 
<e x="1"/> 
<f>foo</f> 
</t> 

產生想要的,正確的結果

<t> 
    <a>2</a> 
    <b/> 
    <d>15</d> 
    <e x="1"/> 
    <f>foo</f> 
</t> 
5

在簡單的情況下,這應該工作:

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

<xsl:template match="*[. = '' or . = '-1']"/> 

有了這個簡單的輸入:

<root> 
    <node></node> 
    <node>-1</node> 
    <node>2</node> 
    <node>8</node> 
    <node>abc</node> 
    <node>-1</node> 
    <node></node> 
    <node>99</node> 
</root> 

結果將是:

<root> 
    <node>2</node> 
    <node>8</node> 
    <node>abc</node> 
    <node>99</node> 
</root>