Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 361
ken Avatar asked Nov 14 '12 16:11

ken


People also ask

What is difference between string empty and null?

The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all.

Is null or empty string?

A string refers to a character's sequence. Sometimes strings can be empty or NULL. The difference is that NULL is used to refer to nothing. However, an empty string is used to point to a unique string with zero length.

Is string null or empty C#?

In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.

Does empty string take up memory?

Note that every string in Python takes additional 49-80 bytes of memory, where it stores supplementary information, such as hash, length, length in bytes, encoding type and string flags. That's why an empty string takes 49 bytes of memory.


2 Answers

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

like image 190
L.B Avatar answered Sep 21 '22 12:09

L.B


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" />
like image 29
Reacher Gilt Avatar answered Sep 19 '22 12:09

Reacher Gilt