Request XML file with LINQ in C #

I have a LINQ query for my XML file and it looks like this:

IEnumerable<XElement> c = from cli in xEl.Elements(ns + "client") where cli.Element(ns+"ID").Value == (((Client)cComboBox.SelectedItem).Id +"") select cli; 

It works fine .. Then I want to repeat this data, so I do it

  foreach (XElement el in c) { } 

my xml file is as follows

  <client> <ID>1</ID> <name>Andrej</name> 

through this iteration I want to extract client values ​​(id → 1 , name → Andrej )

My guess was to put el.Element("name").Value in the middle of the loop, but this does not work ... oh and btw: I am doing this in C # ..

What should I do?

btw2: as you can see, I am new to linq, so I think I left this track ...

Any help would be assigned !! TNX!

+4
source share
2 answers

If I use this code:

  public void Run() { string fileToLoad = this.GetType().Name + ".xml"; XElement root = XElement.Load(fileToLoad); var selected = from cli in root.Elements("client") where cli.Element("ID").Value == "1" select cli; System.Console.WriteLine("Selected:"); foreach (var d in selected) Console.WriteLine("{0}", d.ToString()); System.Console.WriteLine("\nitems:"); foreach (var d in selected) { Console.WriteLine("id: {0}", d.Element("ID")); } } 

And this raw data:

 <root> <client> <ID>1</ID> <name>Andrej</name> </client> <client> <ID>2</ID> <name>William</name> </client> <client> <ID>3</ID> <name>Kate</name> </client> </root> 

Then ... I get this result:

 Selected: <client> <ID>1</ID> <name>Andrej</name> </client> items: id: <ID>1</ID> 
+2
source

You can do this in one statement. I retell your expression. Only the selection changes.

  var nameIdList = (from cli in client where cli.ID == ID select new { id=cli.ID, name=cli.name }).ToList(); 
+1
source

All Articles