xml - Default value for empty node -


i need transform block of xml if node (in case "user/shopid") empty should fallback default value, example "0".

how can accomplished xslt?

xslt 1.0

<xsl:template match="/">     <objects version="product-0.0.1">         <xsl:apply-templates select='users/user'/>     </objects> </xsl:template>  <xsl:template match="user">     <user>         <xsl:attribute name="email"><xsl:value-of select="email"/></xsl:attribute>          <xsl:attribute name="shopid"><xsl:value-of select="shopid"/></xsl:attribute>          <xsl:attribute name="erpcustomer"><xsl:value-of select="erpcustomer"/></xsl:attribute>          <xsl:attribute name="displayname"><xsl:value-of select="displayname"/></xsl:attribute>     </user> </xsl:template> 

for example

<users>   <user>     <email>asdasd@gmail.com</email>     <shopid>123123</shopid>     <erpcustomer>100</erpcustomer>     <displayname>username</displayname>   </user>    <user>     <email>asdasd2@gmail.com</email>     <shopid></shopid>     <erpcustomer>100</erpcustomer>     <displayname>username</displayname>   </user> <users> 

would transformed

<objects version="product-0.0.1">    <user email="asdasd@gmail.com" shopid="123123" erpcustomer="100" displayname="username"></user>    <user email="asdasd2@gmail.com" shopid="0" erpcustomer="100" displayname="username"></user> </objects> 

within code sample change

<xsl:attribute name="shopid"><xsl:value-of select="shopid"/></xsl:attribute>  

to

<xsl:attribute name="shopid">  <xsl:choose>     <xsl:when test="not(normalize-space(shopid))">0</xsl:when>     <xsl:otherwise><xsl:value-of select="shopid"/></xsl:otherwise>  </xsl:choose> </xsl:attribute> 

i consider changing approach template matching , write template

<xsl:template match="users/user/shopid[not(normalize-space())]">   <xsl:attribute name="{name()}">0</xsl:attribute> </xsl:template> 

for special case , preceed with

<xsl:template match="users/user/*">   <xsl:attribute name="{name()}"><xsl:value-of select="."/></xsl:attribute> </xsl:template> 

to handle other transformations.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -