2012-04-10 133 views
6

我的XML文件:选择XML节点使用LINQ to 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节点?

3),当然根据CustomerId你会如何找到这个节点?

+0

我第一次例外: 无法转换类型“WhereEnumerableIterator'1的对象[系统.Xml.Linq.XElement]'键入'System.Xml.Linq.XElement'。 这是因为我试图从IEnumrable投射到一个单一的XElement,我增加第一()扩展到它。 现在它只是无法将x作为XElement。 – 2012-04-10 03:55:24

回答

4

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

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

请注意,这需要客户下方只有一个CustomerId元素。如果有0或> 1,它会抛出异常。看完他的XML后,这可能是合适的。但只是需要指出的一点。 – 2012-04-10 03:59:23

+0

@AndrewFinnell同时是关于这个问题,你将如何去编辑这个节点,我现在可以更新所有客户(的XElement)的死者 但如何将更新文件中的节点? – 2012-04-10 04:06:41

2

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

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

我会调整你的查询是这样的:

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