Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to XML Queries

Let's just say I have an XML file that looks like this:

<?xml version="1.0" encoding="utf-8"?>
<Customers>
  <Customer Name="Jason Voorhees" WeaponPurchased="Machette" SalePrice="499.90" />
  <Customer Name="Michael Myers" WeaponPurchased="Kitchen Knife" SalePrice="96.75" />
</Customers>

Is it possible, with Linq, to do something like this:?

foreach customer in Customers select WeaponPurchased where Name equals "Jason Voorhees"

or:

foreach customer in Customers select customer
label1.Text += "Name: " + customer.Name + Environment.NewLine + "WeaponPurchased: " + customer.WeaponPurchased;

I've seen this type of query before on MSDN, but the links in my favorites lead to the wrong page now, and I'm still trying to find these particular examples. Any help is much appreciated,

Thank you

like image 773
βӔḺṪẶⱫŌŔ Avatar asked May 16 '11 09:05

βӔḺṪẶⱫŌŔ


1 Answers

Try this:

var doc = XDocument.Load(Path.Combine(path, "file.xml"));
var query = from c in doc.Descendants("Customer")
            where c.Attributes("Name").Single().Value == "Jason Voorhees"
            select c.Attributes("WeaponPurchased").Single().Value;

It will return IEnumerable<string> with names of weapons.

like image 102
Ladislav Mrnka Avatar answered Sep 28 '22 08:09

Ladislav Mrnka