使用Linq to XML选择Xml节点

我的Xml文件:

   1f323c97-2015-4a3d-9956-a93115c272ea Aria Stark 1999-01-01T00:00:00   c9c326c2-1e27-440b-9b25-c79b1d9c80ed John Snow 1983-01-01T00:00:00   

我的尝试:

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

这会引发以下exception:

  Object reference not set to an instance of an object. 

1)不是xXElement吗?

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

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

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

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

你没有施放x你正在施放x.Descendants() 。 x.Descendants()返回一个集合,因此复数方法是语义的。 在我的头脑中你应该能够做x.Descendants("CustomerId").FirstOrDefault() as XElement

 XElement toEdit = (from c in doc.Descendants("Customer") where Guid.Parse(c.Value) == customer.CustomerId select c).SingleOrDefault(); 

我会重构您的查询,如下所示:

  XElement toEdit = doc.Descendants("Customer") .Where(x => (Guid)x.Element("CustomerId") == customer.CustomerId) .FirstOrDefault();