Home > Software design >  XSLT with optional template for CSV header
XSLT with optional template for CSV header

Time:04-01

I am new to xslt and hoping to get answer for this.

I have a xslt file and use it to write a csv. First time writing to csv, i would like to have a header. But when I append for next content of csv, I would like to remove the header.

Below is the current xsl. How do I make the xsl template to be optional to display?

<xsl:template name="Header" match="/">
 <xsl:text>Id,Barcode,Name</xsl:text>
    <xsl:apply-templates select="abc:Info/Panel" />
</xsl:template>

<xsl:template name="Panel" match="abc:Info/Panel">
    <xsl:for-each select="Board/Component">
          
      <xsl:value-of select="../../../../../@Id"/>
      <xsl:text>,</xsl:text>
      
      <xsl:value-of select="../../../../../@Barcode"/>
      <xsl:text>,</xsl:text>
          
      <xsl:value-of select="../../../../../@Name"/>
      <xsl:text>,</xsl:text>
    </xsl:for-each>
</xsl:template>

CodePudding user response:

Add a xsl:param to the xslt like i.e. this:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
  xmlns:abc="some-namespace"
  version="1.0" 
  >
  <xsl:param name="writeHeader"                         select="'0'"/>

  <xsl:template  match="/">
    <xsl:if test="$writeHeader='1'">
      <xsl:text>Id,Barcode,Name</xsl:text>
    </xsl:if>
    <xsl:apply-templates select="abc:Info/Panel" />
  </xsl:template>
  
  <xsl:template match="abc:Info/Panel">
    <xsl:for-each select="Board/Component">
      
      <xsl:value-of select="../../../../../@Id"/>
      <xsl:text>,</xsl:text>
      
      <xsl:value-of select="../../../../../@Barcode"/>
      <xsl:text>,</xsl:text>
      
      <xsl:value-of select="../../../../../@Name"/>
      <xsl:text>,</xsl:text>
    </xsl:for-each>
  </xsl:template>
  
</xsl:stylesheet>

And if you want to write the header, call your xsl-transformation with the param: writeHeader=1

  • Related