Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I know the index of a XML Tag

Tags:

c#

linq

How can I get the index of my current XML tag ?

Example:

<User>
  <Contact>
    <Name>Lucas</Name>
  </Contact>
  <Contact>
    <Name>Andre</Name>
  </Contact>
    ...
</User>

I'm trying the code below

    foreach (var element2 in doc2.Root.Descendants())
    {
        String name = element.Name.LocalName;
        String value = element.Value;
    }

I want to know if I'm reading the first <Contact> tag, or the second, or the third...

like image 528
Lucas_Santos Avatar asked Dec 20 '25 11:12

Lucas_Santos


1 Answers

Using the appropriate overload of Select will yield the index as you enumerate the collection.

var userContacts = doc2.Root
                       .Descendants()
                       .Where(element => element.Name == "Contact")
                       .Select((c, i) => new {Contact = c, Index = i});

foreach(var indexedContact in userContacts)
{
     // indexedContact.Contact
     // indexedContact.Index                 
}

Note: I added the .Where because .Descendants will recurse.

like image 60
Austin Salonen Avatar answered Dec 23 '25 01:12

Austin Salonen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!