- <?xml version="1.0" encoding="utf-8" ?>
- <pages>
- <page id="56">
- <img id="teaser" src="img/teaser_company.png"></img>
- </page>
- </pages>
我有一个xml文件为cms内的页面定义了额外的资源.使用LinqToXml查询此文件时,最好的方法来保护Null Reference异常?
- var page = (from tabElement in extensionsDoc.Descendants("page")
- where tabElement.Attribute("id").Value == tabId.ToString()
- select tabElement).SingleOrDefault();
如果页面元素没有名为“id”的属性,则此代码可能会触发Null引用异常.我必须使用try catch块,还是有办法处理这个?例如,如果页面元素没有属性称为“id”,则返回页面对象的null.
编辑:很久以前,这是很清楚的 – 这些天我一定会按照伊戈尔的回答与演员一起去.
最简单的方法是:
- var page = (from tabElement in extensionsDoc.Descendants("page")
- let idAttribute = tabElement.Attribute("id")
- where idAttribute != null
- && idAttribute.Value == tabId.ToString()
- select tabElement).SingleOrDefault();
或者,您可以向XElement编写扩展方法:
- public static string AttributeValueOrDefault(this XElement element,string attributeName)
- {
- XAttribute attr = element.Attribute(attributeName);
- return attr == null ? null : attr.Value;
- }
然后使用:
- var page = (from element in extensionsDoc.Descendants("page")
- where element.AttributeValueOrDefault("id") == tabId.ToString()
- select element).SingleOrDefault();
或使用点符号:
- var page = extensionsDoc.Descendants("page")
- .Where(x => x.AttributeValueOrDefault("id") == tabId.ToString())
- .SingleOrDefault();
(事先调用tabId.ToString(),btw而不是每次迭代都是有意义的.)