简体   繁体   中英

How to search for a set of node using search criteria using Linq to SQL?

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>werer@test.com</EMail>
  </Customer>
  <Customer Id="2">
    <Name>west</Name>
    <DOB>0001-01-01T00:00:00</DOB>
    <EMail>west@test.com</EMail>
   </Customer> 
  <Customer Id="3">
    <Name>west</Name>
    <DOB>0001-01-01T00:00:00</DOB>
    <EMail>west@test.com</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.

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

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

With ToList() extension method.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM