tags:

views:

19

answers:

3

I have this XML

<?xml version="1.0" encoding="utf-8"?>
<Customers>
   <Customer Id="1">
    <Name>rtertr</Name>
    <DOB>2010-12-12T00:00:00</DOB>
    <EMail>[email protected]</EMail>
  </Customer>
  <Customer Id="2">
    <Name>west</Name>
    <DOB>0001-01-01T00:00:00</DOB>
    <EMail>[email protected]</EMail>
   </Customer> 
  <Customer Id="3">
    <Name>west</Name>
    <DOB>0001-01-01T00:00:00</DOB>
    <EMail>[email protected]</EMail>
   </Customer> 
</Customers>

How to fetch all the nodes which have the name as west (<Name>west</Name>) and store it in a collection? In our case it should return 2 nodes (there are two nodes which have Name as west. This has to be achieved using Linq to SQL.

+1  A: 
var doc = XDocument.Parse("<Customers>...</Customers>");

var result = doc.Root
                .Elements("Customer")
                .Where(e => (string)e.Element("Name") == "west")
                .ToList();

or

var doc = XDocument.Parse("<Customers>...</Customers>");

var result = (from e in doc.Root.Elements("Customer")
              where (string)e.Element("Name") == "west"
              select e
             ).ToList();
dtb
A: 

It is not possible to use LINQ to SQL to access XML, unless you first convert the data and store it in an SQL database. It is called LINQ to SQL for a reason. Maybe you mean LINQ to XML so I will assume that.

Assuming you have an XDocument containing the XML:

var customers = myDocument.Root.Descendants()
    .Where(n => n.Name.LocalName == "Customer" &&
                n.Element("Name").Value == "west")
    .ToList();
Timwi
A: 

With ToList() extension method.

 xdoc.Root.Descendants("Customer")
    .Where(c => c.Element("Name").Value == "west")
    .ToList();
Torbjörn Hansson