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"/>

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
  <time day="0" hour="0" minute="0" second="0">a</time>
  <time hour="5" minute="27">b</time>
  <time day="0">c</time>
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="";

<xsl:output method="text"/>

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

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


-- 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? Crane Softwrights Ltd. Training tools: Comprehensive interactive XSLT/XPath 1.0/2.0 video Video lesson: Video overview: G. Ken Holman mailto:gkholman@xxxxxxxxxxxxxxxxxxxx Male Cancer Awareness Nov'07 Legal business disclaimers:

Current Thread