Reputation: 736
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.. Next i want to iterate that data so i do this
foreach (XElement el in c)
{
}
my xml file looks like this
<client>
<ID>1</ID>
<name>Andrej</name>
through that iteration, i want to extract clients values (id -> 1, name -> Andrej)
my guess was to put el.Element("name").Value
in the middle of the loop, but that doesn't work...
oh and btw: i'm doing this in C#..
What do i do?
btw2: as you can see i'm new to linq so i think i'm way off track with this one...
Any help would be appriciated!! TNX!
Upvotes: 4
Views: 15975
Reputation: 192477
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 source 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>
Upvotes: 2
Reputation: 82604
you could do it in one statement. I'm paraphrasing your statement. Only the select really changes.
var nameIdList = (from cli in client
where cli.ID == ID
select new { id=cli.ID, name=cli.name }).ToList();
Upvotes: 1