Reputation: 3819
I don't know why I'm having so much trouble with this, but I'm hoping someone can get me pointed in the right direction.
I have these few lines of code :
var xDoc = new XmlDocument();
xDoc.LoadXml(xelementVar.ToString());
if (xDoc.ChildNodes[0].HasChildNodes)
{
for (int i = 0; i < xDoc.ChildNodes[0].ChildNodes.Count; i++)
{
var sFormatId = xDoc.ChildNodes[0].ChildNodes[i].Attributes["formatID"].Value;
// Do some stuff
}
// Do some more stuff
}
The problem is that the xDoc
I'm getting doesn't always have the formatID
node, so I end up getting a null reference exception, although 99% of the time it works perfectly fine.
My question :
How can I check if the formatID
node exists before I try to read the Value
out of it?
Upvotes: 2
Views: 14632
Reputation: 4076
In most case we face issues because an XPath does not exists, It returns null and our code breaks because of the InnerText.
You can only check XPath exists or not and it returns null when does not exist.
if(XMLDoc.SelectSingleNode("XPath") <> null)
ErrorCode = XMLDoc.SelectSingleNode("XPath").InnerText
Upvotes: 1
Reputation: 101758
I think a cleaner way to do this would be:
var xDoc = new XmlDocument();
xDoc.LoadXml(xelementVar.ToString());
foreach(XmlNode formatId in xDoc.SelectNodes("/*/*/@formatID"))
{
string formatIdVal = formatId.Value; // guaranteed to be non-null
// do stuff with formatIdVal
}
Upvotes: 1
Reputation: 4530
You can also do this:
if (xDoc.ChildNodes[0].HasChildNodes)
{
foreach (XmlNode item in xDoc.ChildNodes[0].ChildNodes)
{
string sFormatId;
if(item.Attributes["formatID"] != null)
sFormatId = item.Attributes["formatID"].Value;
// Do some stuff
}
}
Upvotes: 2
Reputation: 14618
Could you use DefaultIfEmpty()?
E.g
var sFormatId = xDoc.ChildNodes[0].ChildNodes[i].Attributes["formatID"]
.Value.DefaultIfEmpty("not found").Single();
Or as others have suggested, check that the attribute is not null:
if (xDoc.ChildNodes[0].ChildNodes[i].Attributes["formatID"] != null)
Upvotes: 2
Reputation: 32721
you can check that like this
if(null != xDoc.ChildNodes[0].ChildNode[i].Attributes["formatID"])
Upvotes: 1
Reputation: 2378
if a node does not exist, it returns null.
if (xDoc.ChildNodes[0].ChildNode[i].Attributes["formatID"] != null)
sFormatId = xDoc.ChildNodes[0].ChildNodes[i].Attributes["formatID"].Value;
of you can do it a shortcut way
var sFormatId = xDoc.ChildNodes[0].ChildNodes[i].Attributes["formatID"] != null ? xDoc.ChildNodes[0].ChildNodes[i].Attributes["formatID"].Value : "formatID not exist";
The format is like this.
var variable = condition ? A : B;
this is basically saying that if the condition is true, then variable = A, otherwise, variable = B.
Upvotes: 2