Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Xml Node using Linq to 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 throws the following exception :

 Object reference not set to an instance of an object.

1) isn't x an XElement?

2) is this a proper where lambda for selecting an Xml node?

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

like image 217
eran otzap Avatar asked Apr 10 '12 03:04

eran otzap


People also ask

Can we use LINQ for XML?

LINQ to XML provides an in-memory XML programming interface that leverages the . NET Language-Integrated Query (LINQ) Framework. MSDN Says, LINQ to XML is a LINQ-enabled, in-memory XML programming interface that enables you to work with XML from within the . NET Framework programming languages.

What is the difference between XDocument and XmlDocument?

XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument . If you're new to both, check out this page that compares the two, and pick which one you like the looks of better.

Which of the following options is created to retrieve data into XML using LINQ?

The LINQ to XML will bring the XML document into memory and allows us to write LINQ Queries on in-memory XML document to get the XML document elements and attributes. To use LINQ to XML functionality in our applications, we need to add "System. Xml. Linq" namespace reference.

What is System XML LINQ?

LINQ to XML is an in-memory XML programming interface that enables you to modify XML documents efficiently and easily.


1 Answers

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();
like image 199
Andrew Cooper Avatar answered Sep 21 '22 18:09

Andrew Cooper