Search code examples
c#xmlparent-child

How to move from one row to another in an XML file using C# libraries


I have the following structure that I would like to read through in C#. It is used to store a matrix-like set of elements (square in the instance).

<Parent>
    <Child AttrName11="" AttrName12="" AttrName13="" />
    <Child AttrName21="" AttrName22="" AttrName23="" />
    <Child AttrName31="" AttrName32="" AttrName33="" />
</Parent>

I am searching for say a given diagonal attribute value based on an input attribute name, for example, AttrNameXX, and wish to go through the different rows until I get the first match on AttrNameXX, that is, within {AttrName11, AttrName22, AttrName22}. To do so I need to move from one Child to the next.

  • I have opened an

    XmlDocument doc
    
  • I have reached the parent node with

    doc.SelectSingleNode(ParentPath)
    
  • I have reached the first child node with

    doc.SelectSingleNode(ChildPath)
    

I cannot find the command to move to the next child node.


Solution

  • It's as simple as

    XmlNode node = doc.SelectSingleNode(ChildPath);
    var nextNode = node.NextSibling();
    

    Given that you fix your xml, so it's valid of course.

    You can keep calling NextSibling in a loop until it returns null.