简体   繁体   中英

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?

el1.IsEmpty将返回true,另一方面, el2.IsEmpty将返回false。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM