简体   繁体   中英

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> 

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM