Reputation: 173
I have this XML file
<?xml version="1.0" encoding="utf-8"?>
<message>
<success/>
<bookings>
<booking>
<rooms>
<room roomCode ="101" uniqueId="abc">
<stays>
<stay usedfrom="9:30" usedto="10:30" quantity="1" Price="62.5" rateCode="1"/>
</stays>
<extras>
<extra from="9:30" to="10:30" unitPrice="5.5" extraCode="coffee" quantity="1" inclusive="0"/>
</extras>
<guests>
<guest firstName="John" lastName="Doe" title="MR" ageRange="0"/>
</guests>
</room>
<room roomCode ="Brd" uniqueId="xyz">
<stays>
<stay usedfrom="13:30" usedto="15:30" quantity="1" unitPrice="60.0000" rateCode="RACK"/>
</stays>
<guests>
<guest firstName="Jean" lastName="Doe" title="MRS" ageRange="0"/>
</guests>
</room>
</rooms>
</booking>
and i'm trying to run a check to make sure its in the correct format (ie certain elements are present). The code I have been using is
XmlNodeList Successful = doc.GetElementsByTagName("success");
XmlNodeList Bookings = doc.GetElementsByTagName("bookings");
XmlNodeList Booking = doc.GetElementsByTagName("booking");
XmlNodeList Rooms = doc.GetElementsByTagName("rooms");
if ((Successful != null) && (Bookings != null) && (Booking != null) && (Rooms != null))
{
//do something
}
else
{
//do something else
}
This ALWAYS works thought.
If I change the one of the values to
XmlNodeList Rooms = doc.GetElementsByTagName("NoSuchElement");
(which does not exist in the XML) it still "works".
Can someone point out what I've done wrong (I've tried removing the outer brackets from the "if" statement, but this did not change the outcome).
Thanks
Upvotes: 0
Views: 193
Reputation: 37000
As opf the docs:
An XmlNodeList containing a list of all matching nodes. If no nodes match name, the returned collection will be empty.
The method can´t return null
, but an empty list. So check for this instead:
if(theNodeList.Any()) { ... }
else { /* error */ }
Upvotes: 4
Reputation: 23129
This is because oc.GetElementsByTagName("NoSuchElement");
is never null.
As per the documentation, if no element exists, it returns en empty collection which is not null.
You have to check the Count
of the result.
something like :
if (Successful.Count() != 0 && ...)
or
if (!Successful.Any() && ... )
Upvotes: 3