2012-03-20 86 views
3

空XML元素我有以下XML檢查使用XSLT

<ns0:Root xmlns:ns0="http://Map_Sample.Input_Schema"> 
<Number1> 
</Number1> 
<Number2>11</Number2> 
<Number3>12</Number3> 
</ns0:Root> 

在這種情況下,我得到ENTER\r\nNumber1。我想寫一些XSLT來檢查節點是否包含ENTER\r\n,然後替換它<Number1 />

任何人都可以幫我寫XSLT嗎?

回答

10

「空元素」可能意味着什麼有不同的可能定義。

讓我們定義一個空元素作爲一個沒有任何元素節點子元素並且其字符串值爲空字符串或僅由空白字符('',CR,NL)組成的元素。

然後,以檢查是否一個給定的元素是空的,使用

not(*) and not(normalize-space()) 

這假定的元素是上下文節點時XPath表達式進行求值。

在這種情況下,我爲Number1獲取「ENTER」或「\ r \ n」。我想 寫XSLT來檢查節點是否包含「ENTER」或「\ r \ n」,然後替換它 。

您沒有什麼這個文本節點應該更換指定的,所以在這種解決方案我假設文本節點應與空字符串(刪除)被替換爲:

<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(normalize-space())]"> 
    <xsl:element name="{name()}" namespace="{namespace-uri()}"/> 
</xsl:template> 
</xsl:stylesheet> 

當該變換被應用於所提供的XML文檔:

<ns0:Root xmlns:ns0="http://Map_Sample.Input_Schema"> 
    <Number1> 
    </Number1> 
    <Number2>11</Number2> 
    <Number3>12</Number3> 
</ns0:Root> 

有用結果產生

<ns0:Root xmlns:ns0="http://Map_Sample.Input_Schema"> 
    <Number1/> 
    <Number2>11</Number2> 
    <Number3>12</Number3> 
</ns0:Root> 
+0

非常感謝!這給了我想要的確切輸出... – ABC 2012-03-20 16:48:49

+0

@ user1280098:不客氣。 – 2012-03-20 17:33:33

0

嘗試以下方法:

<?xml version="1.0"?> 
<xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

    <xsl:output method="xml" indent="yes"/> 

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

    <xsl:template match="*[normalize-space(string(.)) = '']"/> 
</xsl:stylesheet> 

說明:跳過輸出對於其中(全後代)文本內容是純空白元件。