Graeme
Graeme

Reputation: 155

Distinguish between existing node and empty node

I have 2 Nodes

<example/> and <example></example>.

How can i distinguish between them?

In my mind the first is <xsl:when test="example"> and the second is
<xsl:when test="example = ''">.

I dont think these are right I am confused by this. Can anyone please clarify?

Thanks in advance

Upvotes: 1

Views: 70

Answers (4)

Michael Kay
Michael Kay

Reputation: 163418

They are indistinguishable by design. You could also write

<example   />

or

<example  ></example   >

and those would also be indistinguishable.

These variations are designed to give some flexibility to people authoring or generating XML, without complicating applications that consume XML.

Upvotes: 1

Ian Roberts
Ian Roberts

Reputation: 122384

How can i distinguish between them?

You can't distinguish between them in an XML tool because they're two different ways to serialize exactly the same XML node tree. If your application needs to distinguish between the two cases1 then you'll need to use some sort of non-XML tool, either exclusively or as a pre-processing step.

For example, if you know that there are no instances of the string "/>" within the original file other than as part of an empty element tag, then you could do a textual replacement on the original file (treated as text) to change all instances of

/>

into

 _wasEmpty="yes"/>

(including the leading space) before parsing the result as XML, and then your XSLT can distinguish using <xsl:when test="example[_wasEmpty = 'yes']">.


1 I (and many others on SO) would argue that an application that claims to be XML based but which needs to distinguish between things that XML says are equivalent is fundamentally broken - the correct approach here is to talk to whoever designed the format that you are consuming and ask them to change it to distinguish the cases in an XML-compatible way such as using xsi:nil. But I'm pragmatic and appreciate that sometimes this isn't possible ;-)

Upvotes: 1

Jirka Š.
Jirka Š.

Reputation: 3428

In my opinion - both forms of empty element are equal and it is not possible to distinguish them.

<xsl:when test="example"> tests if there exists some element named "example".

<xsl:when test="example = ''"> tests if the string value of the element is the empty string.

Upvotes: 0

G. Ken Holman
G. Ken Holman

Reputation: 4403

The XML Information Set and the XPath data model state that there is no difference between <example/> and <example></example>:

http://www.w3.org/TR/xml-infoset/#omitted (Item D.7)

http://www.w3.org/TR/2007/REC-xpath-datamodel-20070123/#ElementNode (where you find no property distinguishing the two different syntaxes for an empty element: if the element has no children using either syntax, the element node is constructed the same way)

Upvotes: 1

Related Questions