Re: [xsl] Checking for empty elements

Subject: Re: [xsl] Checking for empty elements
From: "G. Ken Holman" <gkholman@xxxxxxxxxxxxxxxxxxxx>
Date: Wed, 07 Oct 2009 15:18:36 -0400
At 2009-10-07 15:04 -0400, mlcook@xxxxxxxxxx wrote:
Is there a way using XSLT 2.0 to determine whether an element has no
attributes present in an XML document?

That isn't quite what you are asking, though.


Say, given the type, with default values:

<xs:complexType name="TimeType">
    <xs:attribute name="day" type="xs:unsignedByte" default="0"/>
    <xs:attribute name="hour" type="xs:unsignedByte" default="0"/>
    <xs:attribute name="minute" type="xs:unsignedByte" default="0"/>
    <xs:attribute name="second" type="xs:unsignedByte" default="0"/>
</xs:complexType>

And an element definition of that type:

<xs:element name="time" type="myown:TimeType"/>

Is there an <xsl:if test=... /> to determine the difference between the
empty element (which will have default attribute values if processed)
<time />

Right ... which means to the stylesheet it reads, when validation is turned on:


<time day="0" hour="0" minute="0" second="0"/>

which is indistinguishable from an authored:

  <time day="0" hour="0" minute="0"/>
  <time day="0" hour="0" second="0"/>
  ...
  any combination of specified attributes of "0"

and an element with explicit attributes, for example,
<time hour="5" minute="27" />

I'm trying to not process the empty <time /> element.

I have an example below working with XSLT 1 (and so XSLT 2). This works whether or not you have supplied the schema and turned on validation.


I hope this helps.

. . . . . . . . . . . Ken

t:\ftemp>type mlcook.xml
<times>
  <time day="0" hour="0" minute="0" second="0">a</time>
  <time hour="5" minute="27">b</time>
  <time day="0">c</time>
  <time>d</time>
</times>
t:\ftemp>xslt mlcook.xml mlcook.xsl


"Empty": a


Not "empty": b

"Empty": c

"Empty": d

t:\ftemp>type mlcook.xsl
<?xml version="1.0" encoding="US-ASCII"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
                version="1.0">

<xsl:output method="text"/>

<xsl:template match="time">
"Empty": <xsl:value-of select="."/>
</xsl:template>

<xsl:template match="time[@*!='0']">
Not "empty": <xsl:value-of select="."/>
</xsl:template>

</xsl:stylesheet>
t:\ftemp>


-- Upcoming: hands-on code list, UBL, XSLT, XQuery and XSL-FO classes in Copenhagen Denmark and Washington DC USA, October/November 2009 Interested in other classes? http://www.CraneSoftwrights.com/s/i/ Crane Softwrights Ltd. http://www.CraneSoftwrights.com/s/ Training tools: Comprehensive interactive XSLT/XPath 1.0/2.0 video Video lesson: http://www.youtube.com/watch?v=PrNjJCh7Ppg&fmt=18 Video overview: http://www.youtube.com/watch?v=VTiodiij6gE&fmt=18 G. Ken Holman mailto:gkholman@xxxxxxxxxxxxxxxxxxxx Male Cancer Awareness Nov'07 http://www.CraneSoftwrights.com/s/bc Legal business disclaimers: http://www.CraneSoftwrights.com/legal

Current Thread