本文介绍了在Linq To Xml中如何防范Null Reference异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<?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异常。

I have an xml file that defines additional resources for pages within a cms. What's the best way to guard for Null Reference exceptions when querying this file with LinqToXml?

var page = (from tabElement in extensionsDoc.Descendants("page")
where tabElement.Attribute("id").Value == tabId.ToString()
select tabElement).SingleOrDefault();

如果页面元素没有名为 ID。我必须使用try catch块,还是有办法处理这个?例如,如果没有页面元素的名称为id的属性,则返回页面对象的null。

This code could potentially trigger a Null Reference exception if a page element doesn't have an attribute called "id". Do I have to use a try catch block or is there a way to handle this? For instance return null for page the page object if there's no attribute called "id" for the page element.

推荐答案

编辑:很久以前很清楚地写了 - 这些天我一定会按照伊戈尔的回答与演员一起去。

This was clearly written a long time ago - these days I'd definitely go with the cast as per Igor's answer.

最简单的方法是这样的:

The simplest way would be something like:

var page = (from tabElement in extensionsDoc.Descendants("page")
            let idAttribute = tabElement.Attribute("id")
            where idAttribute != null 
                  && idAttribute.Value == tabId.ToString()
            select tabElement).SingleOrDefault();

或者,您可以编写扩展方法到 XElement

Alternatively you could write an extension method to 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,而不是每次迭代。)

(It would make sense to call tabId.ToString() once beforehand, btw, rather than for every iteration.)

这篇关于在Linq To Xml中如何防范Null Reference异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 21:22