qxn
qxn

Reputation: 17584

Differentiate null and string.Empty values in an XElement

I have two instances of XElement:

var el1 = new System.Xml.Linq.XElement("xel", null);
var el2 = new System.Xml.Linq.XElement("xel", string.Empty);

el1 looks like this:

<xel />

el2 looks like this:

<xel></xel>

Yet, the Value property of both is equal to string.Empty.

I can think of plenty of hacks to differentiate null from string.Empty in an XElement, but is there something built into the framework to do this that I'm missing?

Upvotes: 9

Views: 5493

Answers (2)

Reacher Gilt
Reacher Gilt

Reputation: 1813

From the XML Schema Standard:

2.6.2 xsi:nil

XML Schema: Structures introduces a mechanism for signaling that an element should be accepted as ·valid· when it has no content despite a content type which does not require or even necessarily allow empty content. An element may be ·valid· without content if it has the attribute xsi:nil with the value true. An element so labeled must be empty, but can carry attributes if permitted by the corresponding complex type.

So for you, you'd have to add the xsi namespace into your XmlDocument. Then the element would look like

<xel xsi:nil="true" />

Upvotes: 2

L.B
L.B

Reputation: 116178

el1.IsEmpty will return true, on the other hand, el2.IsEmpty will return false.

Upvotes: 6

Related Questions