I want to test if an xml attribute is present. Given this:
XmlAttributeCollection PG_attrColl = SomeNodeorAnother.Attributes;
This first test works:
if (null != PG_attrColl["SomeAttribute"])
"GetNamedItem" is supposed to return null, but the following test throws an exception complaining about the null it returns.
if (null != PG_attrColl.GetNamedItem("SomeAttribute").Value;)
Why the difference开发者_C百科? Just curious.
Because if GetNamedItem
has returned null, you can't call for its Value
member.
if (null != PG_attrColl["SomeAttribute"])
{
string value = PG_attrColl.GetNamedItem("SomeAttribute").Value;
}
Or
object someAttributeNullable = PG_attrColl.GetNamedItem("SomeAttribute");
if (null != someAttributeNullable)
{
string value = someAttributeNullable .Value;
}
if (null != PG_attrColl["SomeAttribute"])
Here you are checking to see if the Attribute is null
if (null != PG_attrColl.GetNamedItem("SomeAttribute").Value;)
Here you are checking to see if the Value of the attribute is null. The code is trying to access the attribute first, which is null, throwing an exception.
精彩评论