Search code examples
c#xmlxmldocumentsiblings

c# xmldocument get all siblings nodes after a specific one


Let's say I have following xml :

<Report>
    <Tablix></Tablix>
    <Textbox Name="TextboxSearchInjection"></Textbox>
    <Textbox></Textbox>
    <Tablix></Tablix>
    <Textbox></Textbox>
    <Textbox Name="TextboxSearchInjectionEnd">
       <Height>1</Height>
    </Textbox>
    <Tablix>
       <Height>1</Height>
    </Tablix>
   <Textbox>
       <Height>2</Height>
    </Textbox>
   <Textbox></Textbox>
   <Tablix>
      <Height>1</Height>
   </Tablix>
   <Textbox>
       <Height>3</Height>
    </Textbox>
</Report>

How to get all siblings nodes after <Textbox Name="TextboxSearchInjectionEnd"> and update value in Height using XmlDocument in c#? So finally I will receive list of nodes like Textbox and Tablix but starting from node <Textbox Name="TextboxSearchInjectionEnd">. I don't want any before.


Solution

  • You could retrieve all succeeding sibling nodes using NextSibling. For Example,

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);
    var node = doc.SelectSingleNode(@"//*[@Name='TextboxSearchInjectionEnd']");
    var result = GetAllSucceedingSiblingNodes(node);
    

    Where GetAllSucceedingSiblingNodes is defined as

    IEnumerable<XmlNode> GetAllSucceedingSiblingNodes (XmlNode node)
    {
        var currentNode = node.NextSibling; // Use currentNode = node if you want to include searched node
        while(currentNode!=null)
        {
            yield return currentNode;
            currentNode = currentNode.NextSibling;
        }
    }