使用LinqtoXML选择Xml节点-440b-9b25-c79b1d9c80edJohnSnow1983-01-01T00:00:00我的尝试:XElementtoEdit=(XElement)doc.Descendants("ArrayOfCustomer").Descendants("Customer").Where(x=>Guid.Parse((x.Descendants("CustomerId")asXElement).Value)==customer.CustomerId).First();这将引发以下异常:未将对象引用设置为对象的实例。1)不是x是XElement?2)这是一个适合选择Xml节点的lambda吗?3)当然,如何根据CustomerId找到这个节点呢?您的问题是Descendents和Where返回IEnumerable而不是您所追求的单个XElement。您可以这样修复:XElementtoEdit=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()asXElementXElementtoEdit=(fromcindoc.Descendants("Customer")whereGuid.Parse(c.Value)==客户.CustomerId选择c).SingleOrDefault();我将按如下方式重构您的查询:以上是C#学习教程:使用LinqtoXML选择Xml节点共享的所有内容。如果对大家有用,需要了解更多C#学习教程,希望大家多多关注——XElementtoEdit=doc.Descendants("Customer").Where(x=>(Guid)x.Element("CustomerId")==customer.CustomerId).FirstOrDefault();本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
