Linq to XML Queries

Let's 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 have seen this type of request before on MSDN, but the links in my favorites now lead to the wrong page, and I'm still trying to find these specific examples. Any help is greatly appreciated

thanks

+6
source share
4 answers

Try the following:

 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 an IEnumerable<string> with weapon names.

+5
source

Try using this query

 XElement root = XDocument.Load(path).Root; var result = root.Elements("Customers"). Where(x => x.Attribute("Name").Value =="Jason Voorhees"). Select(x => x.Attribute("WeaponPurchased").Value)); 

Or you can try to create classes that are defined in xml and deserialize.

+3
source

try it

  public class Customer { public string Name { get; set; } public string WeaponPurchased { get; set; } public string SalePrice { get; set; } } 

and request xml as below

  var customer = from c in XDocument.Load("XMLPATH").Descendants("Customer") where (string)c.Attribute("Name")=="Jason Voorhees" select new Customer { Name=(string)c.Attribute("Name"), WeaponPurchased = (string)c.Attribute("WeaponPurchased"), SalePrice = (string)c.Attribute("SalePrice"), }; foreach (var item in customer) { Console.WriteLine(item.WeaponPurchased); } 
+1
source

Not really.

You want to find Customer , where the attribute has a specific value, and then select the second attribute.

Something else like this:

 from customer in Customers where customer.Attribute("Name").Value equals "Jason Voorhees" select customer.Attribute("WeaponPurchased").Value 
0
source

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


All Articles