是否有一个 GetElementByTagName 来处理标签不存在的情况
我下面有以下代码,但有时“serving_description”标签不存在。现在我只是在它周围尝试捕获,但我想知道是否有更干净的方法来处理这种情况。
XmlElement servingElement = (XmlElement)servingNode;
serving.Id = Convert.ToInt32(servingElement.GetElementsByTagName("serving_id")[0].InnerText);
serving.Name = servingElement.GetElementsByTagName("serving_description")[0].InnerText;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我宁愿检查返回的 NodeList 是否不为 null,并在使用默认为 try 之前检查计数是否大于零抓住。
一些简单的东西,比如
EDIT
如果我没记错的话,您甚至可能不需要检查 null 因为 GetElementsByTagName 方法可能只返回一个空列表(但我现在无法验证,抱歉)
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
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)