Groups | Blog | Home
all groups > dotnet xml > january 2005 >

dotnet xml : Newbie: How do you test for Attribute existence in C#/VB.NET?


Larry Woods
1/26/2005 3:47:52 AM
How do I test for the existence of a nodal attribute?

The following snippet terminates with an error "Object reference not set to
an instance of an object."

Snippet:

For Each oChild In oNode.ChildNodes
If Not (oChild.Attributes.ItemOf("key") Is Nothing) Then
...............................
End of Snippet

Testing in Intermediate mode:

? ochild.Attributes.ItemOf("key")
Referenced object has a value of 'Nothing'.

So, why doesn't the "Is Nothing" test work?

TIA,
Larry Woods

Larry Woods
1/26/2005 8:35:24 AM
Thanks, Martin,

I should have seen that. Testing oChildAttributes worked fine.

Larry

[quoted text, click to view]

Martin Honnen
1/26/2005 1:12:55 PM


[quoted text, click to view]

It could be that the For Each loop finds a child node which is not an
element node and therefore doesn't have attributes at all, in that case
oChild.Attributes is null in C# (which I think is Nothing in VB.NET) and
then the attempt to access .ItemOf on null (respectively Nothing) causes
the error.
So you need to make sure you have an element node by checking NodeType
for instance before you try to access Attributes.

--

Martin Honnen
AddThis Social Bookmark Button