Select an Xml Node with Linq for XML

my xml file:

<?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>(); 

this raises the following exception:

  Object reference not set to an instance of an object. 

1) not x an XElement ?

2) is this correct when lambda to select Xml node?

3) and, of course, how do you find this node according to CustomerId ?

+6
source share
4 answers

Your problem is that Descendents and Where return IEnumerable<XElement> not the one XElement you need. You can fix it as follows:

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

You don't throw x , you throw x.Descendants() . x.Descendants () returns a collection, therefore the semantic plural method. On top of my head, you can do x.Descendants("CustomerId").FirstOrDefault() as XElement

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

I would restructure your request as follows:

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

Source: https://habr.com/ru/post/912811/


All Articles