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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With