CodeGo.net>当.Count()大于零时,从.Select()获取NullReferenceException LINQ to XML
作者:互联网
我有一个XML文件:
<Org href="https://vcloudserver/api/v1.0/org/272521719" type="application/vnd.vmware.vcloud.org+xml" name="blah-blah" xmlns="http://www.vmware.com/vcloud/v1">
<Link href="https://vcloudserver/api/v1.0/vdc/1093121285" type="application/vnd.vmware.vcloud.vdc+xml" name="blah-haha" rel="down"/>
<Link href="https://vcloudserver/api/v1.0/vdc/1213262741" type="application/vnd.vmware.vcloud.vdc+xml" name="blah-hoho" rel="down"/>
<Link href="https://vcloudserver/api/v1.0/tasksList/272521719" type="application/vnd.vmware.vcloud.tasksList+xml" rel="down"/>
<Link href="https://vcloudserver/api/v1.0/catalog/1309520800" type="application/vnd.vmware.vcloud.catalog+xml" name="blah-hehe" rel="down"/>
<Link href="https://vcloudserver/api/v1.0/org/272521719/catalog/1309520800/controlAccess/" type="application/vnd.vmware.vcloud.controlAccess+xml" rel="down"/>
<Link href="https://vcloudserver/api/v1.0/org/272521719/catalog/1309520800/action/controlAccess" type="application/vnd.vmware.vcloud.controlAccess+xml" rel="controlAccess"/>
<Link href="https://vcloudserver/api/v1.0/network/1435818199" type="application/vnd.vmware.vcloud.network+xml" name="blah-whodat" rel="down"/>
<Link href="https://vcloudserver/api/v1.0/network/2048048931" type="application/vnd.vmware.vcloud.network+xml" name="blah-disis" rel="down"/>
<Description/>
<FullName>Blah diddy Blah-Blah</FullName>
</Org>
因此,鉴于以下情况:
XNamespace nameSpace = "http://www.vmware.com/vcloud/v1";
var doc = XDocument.Parse(xml);
当我在VS立即窗口中调试以下代码时:
doc.Root.Elements(nameSpace + "Link").Count()
我得到的期望值为8.但是当我进一步使用以下方法时:
var vdcs = doc.Root.Elements(nameSpace + "Link")
.Select(x => new vDC()
{
Name = x.Attribute("name").Value,
Type = x.Attribute("type").Value,
Href = x.Attribute("href").Value
}).Where(x=>x.Type.Contains("vdc"));
我在尝试访问vdcs.Count()时收到NullReferenceException.我已经把这个问题弄得太久了……在其他地方,这种类型的事情可以正常工作,所以这无济于事. :(尝试在Where()之前填充ToList(),然后将NullReferenceException移至该调用.
如果有帮助,vDC当前定义为:
public class vDC
{
public string Name { get; set; }
public string Type { get; set; }
public string Href { get; set; }
}
解决方法:
您的某些链接没有名称-而是rel. NPE来自此.
您只有在致电Count时才能看到它,因为直到那时才进行实际评估.
要更改代码以防NPE,请添加Where条件:
var vdcs = doc.Root.Elements(nameSpace + "Link")
.Where(x => x.Attribute("name") != null && x.Attribute("type") != null && x.Attribute("value") != null)
.Select(x => new vDC {
Name = x.Attribute("name").Value,
Type = x.Attribute("type").Value,
Href = x.Attribute("href").Value
}).Where(x=>x.Type.Contains("vdc"));
标签:linq-to-xml,linq,xml,c 来源: https://codeday.me/bug/20191201/2084626.html