6

我的 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.

x1 )不是XElement吗?

2) 这是选择 Xml 节点的正确 where lambda 吗?

3)当然你会如何找到这个节点CustomerId

4

4 回答 4

4

你的问题是,DescendentsWhere返回一个IEnumerable<XElement>不是XElement你所追求的。你可以像这样解决这个问题:

XElement toEdit = doc.Descendants("ArrayOfCustomer")
                     .Descendants("Customer")
                     .Where(x => Guid.Parse(x.Descendants("CustomerId").Single().Value) == customer.CustomerId)
                     .FirstOrDefault();
于 2012-04-10T03:55:54.313 回答
2

你不是在铸造x,你在铸造x.Descendants()。x.Descendants() 返回一个集合,因此是复数方法语义。在我的脑海中,你应该能够做到x.Descendants("CustomerId").FirstOrDefault() as XElement

于 2012-04-10T03:54:37.533 回答
1
XElement toEdit = (from c in doc.Descendants("Customer")
     where Guid.Parse(c.Value) == customer.CustomerId
     select c).SingleOrDefault();
于 2012-04-10T03:57:17.620 回答
1

我会像这样重组您的查询:

 XElement toEdit = doc.Descendants("Customer")
                      .Where(x => (Guid)x.Element("CustomerId") == customer.CustomerId)
                      .FirstOrDefault();
于 2012-04-10T04:00:32.353 回答