加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用Linq to XML选择Xml节点

发布时间:2020-12-15 04:35:59 所属栏目:百科 来源:网络整理
导读:我的Xml文件: ?xml version="1.0" encoding="utf-8"?ArrayOfCustomer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Customer CustomerId1f323c97-2015-4a3d-9956-a93115c272ea/CustomerId FirstNa
我的Xml文件:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfCustomer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Customer>
        <CustomerId>1f323c97-2015-4a3d-9956-a93115c272ea</CustomerId>
        <FirstName>Aria</FirstName>
        <LastName>Stark</LastName>
        <DOB>1999-01-01T00:00:00</DOB>
    </Customer>
    <Customer>
        <CustomerId>c9c326c2-1e27-440b-9b25-c79b1d9c80ed</CustomerId>
        <FirstName>John</FirstName>
        <LastName>Snow</LastName>
        <DOB>1983-01-01T00:00:00</DOB>
    </Customer>
</ArrayOfCustomer>

我的尝试:

XElement toEdit = 
    (XElement)doc.Descendants("ArrayOfCustomer")
                 .Descendants("Customer")
                 .Where(x => Guid.Parse((x.Descendants("CustomerId") as XElement).Value) == customer.CustomerId)
                 .First<XElement>();

这会引发以下异常:

Object reference not set to an instance of an object.

1)不是x一个XElement?

2)这是一个适合选择Xml节点的lambda吗?

3)当然,您如何根据CustomerId找到此节点?

解决方法

你的问题是后代和Where返回IEnumerable< XElement>没有一个XElement是你所追求的.你可以像这样解决这个问题:
XElement toEdit = doc.Descendants("ArrayOfCustomer")
                     .Descendants("Customer")
                     .Where(x => Guid.Parse(x.Descendants("CustomerId").Single().Value) == customer.CustomerId)
                     .FirstOrDefault();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读