2017-09-05 164 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>