8

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?

qxn
  • 17,162
  • 3
  • 49
  • 72
  • 3
    The way to indicate null is to **omit** the element entirely. An element that is present is going to parse with a non-null Value. – Anthony Pegram Nov 14 '12 at 16:32
  • @AnthonyPegram that's possible, unless there's a schema that specifies xel with a MinOccurs > 0. This seems to happen pretty frequently for whatever reason in my sector. – Reacher Gilt Nov 14 '12 at 16:44
  • 1
    According to the XML standard, `` and `` **must** be equivalent. So to differentiate between `""` and `null` for strings, either follow Anthony's suggestion above, or use an attribute inside the element, like ``. – Jeppe Stig Nielsen Nov 14 '12 at 16:45
  • See also http://stackoverflow.com/a/7250336/1336654 – Jeppe Stig Nielsen Nov 14 '12 at 17:25

2 Answers2

6

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

L.B
  • 114,136
  • 19
  • 178
  • 224
  • 1
    Correct, but I don't think you should use `IsEmpty` because the semantics of `el1` and `el2` must be identical. MSDN's XML reference also [writes](http://msdn.microsoft.com/en-us/library/ms256085.aspx): _In XML, you can indicate an empty element with start and end tags and no white space or content in between, for example, ``, or you can use an empty tag, for example, ``. The two forms produce identical results in an XML parser._ – Jeppe Stig Nielsen Nov 14 '12 at 17:34
  • @JeppeStigNielsen - The comments and the other answer bring up very good points, but I think this answers the question most directly. I was probably a little unclear, but my question is really, "What property of XElement differentiates between an element with a closing tag and an element with no closing tag?" – qxn Nov 14 '12 at 18:11
2

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" />
Reacher Gilt
  • 1,813
  • 12
  • 26