Search code examples
c#xmlxpathxmldocument

Navigate between XML Elements with Same Attribute


I'm working on a C#/ASP.Net project.

Let's say this is an xml document:

parent1
    child1 attributeA
    child2 attributeA

parent2
    child3 attributeA
    child4 attributeB

I want to navigate with next and previous buttons between anything with attributeA, so if I'm at parent1/child2, next would be parent2/child3 and previous would be parent1/child1.

I can create a new XML Document, I can load it, and I can get the current node, but I don't know about next and previous.

How can I do that? Haven't done xpaths in a while. A LONG while. I looked around here for something similar but either it's not there or I can't find it.

Can anyone help?


Solution

  • The MSDN has a nice article about XPaths with great examples

    But this code should give you all the nodes that have attributeA regardless of where they are nested in the XML:

    var doc = new XmlDocument();
    doc.Load(@"C:\path\to\file.xml");
    XmlNodeList nodes = doc.SelectNodes("//*[@attributeA]");
    foreach (var node in nodes)
    {
        // your code here
    }
    

    The path //*[@attributeA] boils down to:

    // "one or more levels deep"

    * "any element"

    [@attributeA] "with attribute 'attributeA'"