Gaurav Thantry
Gaurav Thantry

Reputation: 803

null value must be printed if there is no value for the xml element

I am supposed to write an XSLT for an XML document, for which if it has no parameter for an element, the XSLT must consider a null value. The output must be an XML document where the elements with no values in the original xml document, must be printed as <tagName>Null</tagName>

This is the xml document

<salesOrderRequest>
<invoiceNo>1245</invoiceNo>
<PizzaType/>
<Price>1099</Price>
<Discount>234</Discount>
</salesOrderRequest>

This is my xslt

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XMLTransform">
 <xsl:template match="/">
  <xsl:for-each select="/salesOrderRequest">
   <xsl:value-of select="invoiceNo"/>
   <xsl:value-of select="PizzaType"/>
   <xsl:value-of select="Price"/>
   <xsl:value-of select="Discount"/>
  </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>

<salesOrderRequest>
    <invoiceNo>1245</invoiceNo>
    <PizzaType>Null</PizzaType>
    <Price>1099</Price>
    <Discount>234</Discount>
    </salesOrderRequest>

Upvotes: 0

Views: 1205

Answers (2)

Michael Kay
Michael Kay

Reputation: 163458

Try:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XMLTransform">

  <xsl:template match="/">
    <xsl:apply-templates select="/salesOrderRequest/*"/>
  </xsl:template>

  <xsl:template match="salesOrderRequest/*" priority="1">
     <xsl:value-of select="."/>
  </xsl:template>

  <xsl:template match="salesOrderRequest/*[.='']" priority="2">
     <xsl:text>null</xsl:text>
  </xsl:template>

</xsl:stylesheet>

Upvotes: 1

C. M. Sperberg-McQueen
C. M. Sperberg-McQueen

Reputation: 25034

In XSLT 2.0 or 3.0, for

try

<xsl:value-of select="if (normalize-space(PizzaType))
    then PizzaType
    else 'Null' "/>

or (if you don't want to accept <PizzaType> </PizzaType> as equivalent to <PizzaType/>)

<xsl:value-of select="if (PizzaType ne '')
    then PizzaType
    else 'Null' "/>

or

<xsl:value-of select="(PizzaType[. ne ''], 'Null')[1]"/>

If you require a solution in XSLT 1.0, you should tag your question that way.

Upvotes: 1

Related Questions