2017-05-08 82 views
0

我有一個XML象下面這樣:檢查空值和忽略標籤XSLT

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
    <properties> 
    <entry key="user">1234</entry> 
    <entry key="name"></entry> 
    </properties> 

我要檢查如果鍵「名」爲空值,如果爲null,則忽略完整的標籤和結果XML應該是這樣的:

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
    <properties> 
    <entry key="cm:user">1234</entry> 
    </properties> 

如果不爲空,則結果XML應該是這樣的:

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
    <properties> 
    <entry key="cm:user">1234</entry> 
    <entry key="cm:name">sam</entry> 
    </properties> 

我使用下面的xslt,但沒有得到所需的輸出。

<xsl:template match="@key[.='user']"> 
<xsl:attribute name="key"> 
     <xsl:value-of select="'cm:user'"/> 
    </xsl:attribute> 
</xsl:template> 

<xsl:choose> 
<xsl:when test="@key[.='name'] != ''"> 
    <xsl:template match="@key[.='name']"> 
<xsl:attribute name="key"> 
     <xsl:value-of select="'cm:name'"/> 
</xsl:attribute> 
</xsl:template> 
</xsl:when> 
<xsl:otherwise> 
<xsl:template match="entry[@key='name']"/> 
</xsl:otherwise> 
</xsl:choose> 

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

<xsl:variable name="fileName"> 
       <xsl:value-of select="base-uri()" /> 
</xsl:variable>  

<xsl:template match="/">   
<xsl:result-document href="{$fileName}.xml"> 
    <xsl:apply-templates/> 
    </xsl:result-document> 
</xsl:template> 

</xsl:transform> 

可能有人請幫我這得到所需的輸出XML。

回答

1

難道你不能簡單地說:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> 
<xsl:strip-space elements="*"/> 

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

<xsl:template match="entry"> 
    <entry key="cm:{@key}"> 
     <xsl:apply-templates/> 
    </entry> 
</xsl:template> 

<xsl:template match="entry[@key='name'][not(string())]"/> 

</xsl:stylesheet> 
+0

它的偉大工程。謝謝,邁克爾。 –