使用LINQ to XML选择XML节点 [英] Select Xml Node using Linq to XML
本文介绍了使用LINQ to XML选择XML节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的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>
我尝试:
my attempt :
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节点?
2) is this a proper where lambda for selecting an Xml node?
3),当然你会如何根据客户ID
?
3) and of course how would you find this node according to CustomerId
?
推荐答案
您的问题是,后裔
和其中,
返回的IEnumerable<&的XElement GT;
不是一个单一的的XElement
这就是你追求的。你可以这样解决这个问题:
Your problem is that Descendents
and Where
return an IEnumerable<XElement>
not a single XElement
which is what you're after. You can fix this like this:
XElement toEdit = doc.Descendants("ArrayOfCustomer")
.Descendants("Customer")
.Where(x => Guid.Parse(x.Descendants("CustomerId").Single().Value) == customer.CustomerId)
.FirstOrDefault();
这篇关于使用LINQ to XML选择XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文