Click here to Skip to main content
15,885,216 members
Articles / Programming Languages / XML

Determining nil in an XML Element

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
19 Feb 2013CPOL 10.2K   5  
How to determine nil in an XML element

I have been trying to find a way to determine if an XML element is marked as null. There isn't built in support in .NET 4 or earlier versions. So, after doing some research (Dimuthu's Blog: XML Schema nillable=“true” vs minOccurs=“0”XLinq xsi:nil=“true”, Do XML parsers tell the difference between xsi:nil=“true” and omitted elements?), I came up with the following function to determine if an element is marked as nil.

VB.NET
Function ElementIsNil(ByVal XData As XElement) As Boolean
  Dim XElementNil As XName = "{http://www.w3.org/2001/XMLSchema-instance}nil"
  Dim bResult As Boolean

  Dim oAttrNull = From xList As XAttribute
                  In XData.Attributes
                  Where xList.Name = "{http://www.w3.org/2001/XMLSchema-instance}nil"
                  Take 1

  If oAttrNull.Count = 0 Then
    bResult = False
  Else
    bResult = (oAttrNull(0).Value = True)
  End If

  Return bResult
End Function

Here's some code to exercise the above function:

VB.NET
Dim xData As XElement =
  <Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Trunk>
      <Limb>1</Limb>
      <Limb></Limb>
      <Limb xsi:nil="true" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
      <Limb xsi:nil="true"/>
      <Limb xsi:nil="false"/>
      <Limb>6</Limb>
    </Trunk>
  </Root>

For Each oLimb In xData.<Trunk>.<Limb>
  String.Format("IsNothing: {2}, Value: ""{1}"", _
  IsNil: {3}, ToString: {0}", oLimb.ToString(), oLimb.Value, _
  Microsoft.VisualBasic.IsNothing(oLimb), ElementIsNil(oLimb)).Dump()
Next

Sample output:

IsNothing: False, Value: "1", IsNil: False, ToString: 1
IsNothing: False, Value: "", IsNil: False, ToString: <limb></limb>
IsNothing: False, Value: "", IsNil: True, ToString: 
<limb xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"></limb>
IsNothing: False, Value: "", IsNil: True, ToString: 
<limb xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"></limb>
IsNothing: False, Value: "", IsNil: False, ToString: 
<limb xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="false"></limb>
IsNothing: False, Value: "6", IsNil: False, ToString: 6

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
Long time software engineer who rambles occasionally about coding, best practices, and other random things.

Comments and Discussions

 
-- There are no messages in this forum --