Santhosh
Santhosh

Reputation: 55

Check for null value and Ignore the tag XSLT

I have an xml like below:

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

I want to check if the value of the key "name" for null, if null then ignore the complete tag and the result xml should look like this:

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

If not null then the result xml should look like this:

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

I am using the below xslt but not getting the desired output.

<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>

Could someone please help me with this to get the desired output xml.

Upvotes: 0

Views: 1260

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116982

Couldn't you do simply:

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>

Upvotes: 1

Related Questions