C#LINQ to XML空值异常

编程入门 行业动态 更新时间:2024-10-10 00:21:56
本文介绍了C#LINQ to XML空值异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是我的代码:

List<Customer> customersList = ( from e in XDocument.Load(file).Root.Elements("cust") select new Customer { CustomerID = (int)e.Element("custid"), FirstName = (string)e.Element("fname"), LastName = (string)e.Element("lname"), ShowsNumber = (int)e.Element("count_noshow"), VisitNumber = (int)e.Element("count_resos"), Cancellation = (int)e.Element("count_cancel"), }).ToList();

我在代码的customerList = (....)部分出现了{"Value cannot be null.\r\nParameter name: element"}异常,

I got {"Value cannot be null.\r\nParameter name: element"} exception on the customerList = (....) part of the code,

我可以看到XML,它在root节点下有很多cust节点.

I can see the XML, it has a lot of cust nodes under the root node.

你能帮我吗?

非常感谢 最好的问候,

Many thanks Best regards,

XML:

<root source="ERB" versionmajor="5" versionminor="0" filetype="3PCustomer"> <cust rid="303" custid="5" lname="Test" fname="Test" emailoptin="1" mailoptin="1" datecreated="2006-01-12T15:37:54.450" count_resos="2" count_noshow="0" count_cancel="0"> <phone phonenumber="408.123.4567" countrycodeid="1" phonetype="Home"/> <custcode ccode="Vegetarian"/> </cust> <cust rid="303" custid="6" lname="John" fname="Doe" email="johnD@ot" emailoptin="0" mailoptin="1" cnotes="Half caf double de-caf, with a twist..." datecreated="2006-01-12T17:09:57.013" count_resos="2" count_noshow="0" count_cancel="0"> <phone phonenumber="456.456.4565" countrycodeid="1" phonetype="Home"/> <custcode ccode="Guest Share"/> </cust> <cust rid="303" custid="7" webcustid="1654438" lname="doe" fname="john" emailoptin="1" mailoptin="1" datecreated="2006-01-13T11:04:25.653" count_resos="1" count_noshow="0" count_cancel="0"> <phone phonenumber="123.456.7890" countrycodeid="1" phonetype="Home"/> </cust> <!-- (...) --> </root>

推荐答案

您选择的是Element(),但custid,fname等不是元素,而是attributes.

You are selecting Element(), but custid, fname, etc.are not elements rather they are attributes.

像这样更新它:-

List<Customer> customersList = ( from e in XDocument.Load(file).Root.Elements("cust") select new Customer { CustomerID = (int)e.Attribute("custid"), FirstName = (string)e.Attribute("fname"), LastName = (string)e.Attribute("lname"), ShowsNumber = (int)e.Attribute("count_noshow"), VisitNumber = (int)e.Attribute("count_resos"), Cancellation = (int)e.Attribute("count_cancel"), }).ToList();

更多推荐

C#LINQ to XML空值异常

本文发布于:2023-06-10 18:40:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/616539.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常   LINQ   XML

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!