views:

96

answers:

1

i have the following code below but sometime the "serving_description" tag isn't there. Right now i just put a try catch around it but i wanted to find out 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;
+3  A: 

I would rather check that the returning NodeList is not null and check that the count is greater than zero before using defaulting to a 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 am not mistaken, you might not even have to check for the null as the GetElementsByTagName method might just return an empty list(but I cannot verify that right now, sorry)

astander
@astander - from memory, I think you're right - you get an empty (but non-null) node-set.
Marc Gravell