首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > .NET >

Linq查询XML属性替空时,绑定数据出错

2012-09-09 
Linq查询XML属性为空时,绑定数据出错!var testfrom c in xd.Element(people).Elements()select new{编

Linq查询XML属性为空时,绑定数据出错!
var test=from c in xd.Element("people").Elements()  
  select new
  {
  编号=c.Attribute("ID").Value,  
  姓名=c.Attribute("Name").Value,
  };

  GvXML.DataSource = text;
  GvXML.DataBind();
   


如上,如果XML文件中姓名属性为空的话 <person ID="1" Name="" > ,就会出现 “未将对象引用设置到对象的实例。”的错误。尝试过修改:  
  姓名=c.Attribute("Name").Value,
  为:
  姓名=(c.Attribute("Name").Value==null?"null":c.Attribute("Name").Value),
还是一样出错,不知道怎么解决?

[解决办法]
c.Attribute("Name") == null ? "null":c.Attribute("Name").Value

热点排行