There is a GetElementByTagName that handles if the tag is not there
I have the following code below, but sometimes the "serve_description" tag doesn't exist. Right now I just put in an attempt to catch it, but I wanted to know if there was a cleaner way to handle this scenario.
XmlElement servingElement = (XmlElement)servingNode;
serving.Id = Convert.ToInt32(servingElement.GetElementsByTagName("serving_id")[0].InnerText);
serving.Name = servingElement.GetElementsByTagName("serving_description")[0].InnerText;
+2
a source to share
1 answer
I would rather check that the returned NodeList is not null and checks that the counter is greater than zero before using the default try catch.
Something simple like
serving.Name = "defaultName";
XmlNodeList elemList = servingElement.GetElementsByTagName("serving_description");
if (elemList != null && elemList.Count > 0)
serving.Name = elemList[0].InnerText;
EDIT
If I'm not mistaken, you might not even need to check for null, as the GetElementsByTagName method might just return an empty list (but I can't check that now, sorry)
+3
a source to share