Tone
Tone

Reputation: 33

XSLT - Remove empty tag after transformation

I am trying to remove all empty elements after I have finished the transformation however I am just not coming right. I have the following XML

<root>
  <record name='1'>
    <Child1>value1</Child1>
    <Child2>value2</Child2>
  </record>
  <record name='2'>
    <Child1>value1</Child1>
    <Child2>value2</Child2>
  </record>
  <record name='3'>
    <Child1>value1</Child1>
    <Child2>value2</Child2>
  </record>
</root>

and I want the output to be

<root>
  <record name="1">
    <Element>1</Element>
  </record>
</root>

however I keep getting all the empty record elements as well and I can't figure out how to get rid of them.

<root>
  <record>
    <Element>1</Element>
  </record>
  <record/>
  <record/>
</root>

This is my stylesheet

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

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

  <xsl:template match="//record">
    <xsl:copy>
      <xsl:call-template name="SimpleNode"/>    
    </xsl:copy>
  </xsl:template>

  <xsl:template name="SimpleNode">
    <xsl:if test="@name = '1'">
      <Element><xsl:value-of select="@name"/></Element>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

Upvotes: 1

Views: 1415

Answers (1)

Ben L
Ben L

Reputation: 1312

I would rewrite your XSLT a little to match record elements differently depending on the value of their @name attribute.

The following XSLT stylesheet:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
  <xsl:strip-space elements="*"/>

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

  <!-- Only produce output for record elements where the name attribute is 1. -->
  <xsl:template match="record[@name='1']">
    <xsl:copy>
      <element>
        <xsl:value-of select="@name"/>
      </element>
    </xsl:copy>
  </xsl:template>

  <!-- For every other record attribute, output nothing. -->
  <xsl:template match="record"/>
</xsl:stylesheet>

produces the following output when applied to your example input XML:

<root>
  <record>
    <element>1</element>
  </record>
</root>

Upvotes: 2

Related Questions