4

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!

1
  • sorry just to be clear do you want to get the elements which have an id = 1 or an id => 1 ? Commented Apr 29, 2011 at 12:35

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Also I had an issue where I had XmlNodes and needed to convert to XmlElements. Here is a good link for how to add this to your Extensions class. blogs.msdn.com/b/ericwhite/archive/2008/12/22/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.