2010-12-10 58 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>