Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xslt to add default value where element doesn't exist

Tags:

xslt

I'm struggling with trying to test to see if an element exists. If it doesn't, I'd like to add in a default value. Here's my XML

<records>
  <record>
    <InstanceData>
      <instance>
        <FirstName>Johhny</FirstName>
        <LastName>Jenkins</LastName>
        <AlbumCount>3</AlbumCount>
      </instance>
    </InstanceData>
  </record>
  <record>
    <InstanceData>
      <instance>
        <FirstName>Art</FirstName>
        <LastName>Tatum</LastName>
        <AlbumCount>7</AlbumCount>
      </instance>
    </InstanceData>
  </record>
  <record>
    <InstanceData>
      <instance>
        <FirstName>Count</FirstName>
        <LastName>Basie</LastName>
      </instance>
    </InstanceData>
  </record>
</records>

I'd like to be able to copy over existing values and set any record without the Album Count element to <AlbumCount>0</AlbumCount>. This is the xslt I've been working with but I think I'm some way off the mark.

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  version="1.0"> 
  <xsl:template match="Records">
    <xsl:for-each select="node()">
      <xsl:choose>
        <xsl:when test="name()='AlbumCount'">
          <xsl:element name="AlbumCount">
            <xsl:choose>
              <xsl:when test="name()='AlbumCount'">
                <xsl:copy-of select=".">
                </xsl:copy-of>
              </xsl:when>
              <xsl:otherwise>
                <AlbumCount>0</AlbumCount>
              </xsl:otherwise>
            </xsl:choose>
          </xsl:element>
        </xsl:when>
        <xsl:otherwise>
          <xsl:copy-of select=".">
          </xsl:copy-of>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

Thanks for looking.

like image 460
Willb Avatar asked Dec 22 '22 11:12

Willb


1 Answers

Try this:

<?xml version="1.0" encoding="UTF-8"?>
<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" omit-xml-declaration="no"/>

<!-- identity template -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="instance[not(AlbumCount)]">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
        <AlbumCount>0</AlbumCount>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>   

Start with the identity transformation, then just handle the exception differently.

like image 59
Jon Egerton Avatar answered Jan 06 '23 00:01

Jon Egerton