2017-09-05 134 views
1

我正在寻找帮助 我正在写一个XSL来删除空节点,它正在工作,但如果我在其中一个XML节点中有xsi:xsi = true,那么它不会删除该节点,我需要其删除空节点,该节点包含的xsi空属性和节点样式表:的xsi =真使用XSLT删除空的XML节点

INPUT XML

<root> 
<para> 
<Description>This is my test description</Description> 
<Test></Test> 
<Test1 attribute="1"/> 
<Received_Date xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/> 
</para> 
</root> 

输出XML

<root> 
<para> 
<Description>This is my test description</Description> 
<Test1 attribute="1"/> 
<Received_Date xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/> 
</para> 

期望输出

<root> 
<para> 
<Description>This is my test description</Description> 
<Test1 attribute="1"/> 
</para> 
</root> 

XSL代码

<?xml version="1.0" ?> 

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:output omit-xml-declaration="yes" indent="yes" /> 
    <xsl:template match="node()|SDLT"> 
     <xsl:if test="count(descendant::text()[string-length(normalize-space(.))>0]|@*)"> 
      <xsl:copy> 
       <xsl:apply-templates select="@*|node()" /> 
      </xsl:copy> 
     </xsl:if> 

    </xsl:template> 
    <xsl:template match="@*"> 
     <xsl:copy /> 
    </xsl:template> 
    <xsl:template match="text()"> 
     <xsl:value-of select="normalize-space(.)" /> 
    </xsl:template> 

</xsl:stylesheet> 
+1

'XSI:nil'是一个属性,样式表不考虑的要素具有“空”的属性。 –

+0

另外,你为什么要匹配名为'SDLT'的元素?这个元素似乎不存在于任何输入文件中,无论如何,这已经被任何'node()'的匹配所覆盖。 –

+0

是的,我同意,我们不需要SDLT。对我来说,我需要删除具有属性xsi:nil = true的元素 – user2631055

回答

0

您可以使用此:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    version="1.0"> 
    <xsl:output omit-xml-declaration="yes" indent="yes" /> 
    <xsl:template match="node()|SDLT"> 
     <xsl:if test="(node() or @*) and not(@xsi:nil = 'true')"> 
      <xsl:copy> 
       <xsl:apply-templates select="@*|node()" /> 
      </xsl:copy> 
     </xsl:if> 

    </xsl:template> 

    <xsl:template match="@*"> 
     <xsl:copy /> 
    </xsl:template> 

    <xsl:template match="text()"> 
     <xsl:value-of select="normalize-space(.)" /> 
    </xsl:template> 

</xsl:stylesheet>