Search code examples
c#xmlwpfnodeschild-nodes

Find xml node in deeper levels recursively in c#


I am trying to get the node in deep level for the xml structure.

My xml Structure:

<Level1 name="data_reply"> 
  <Level2 name="name1"> 
    <level3 name="name2" />
    <Level3 name="name3 > 
        <Level4 name="name4"/>
        <Level4 name="name5" someAttributes="blah blah"/>
    </Level3> 
  <Level2 name="name6"/>
  <Level2 name="name7"/>
</Level1> 

I want to get the node named with "name 5" and it's attributes. The problem is i want to get this node even if it was deeper or the node levels are different. name attributes can be assumed as unique I mean that what i want is something like:

var xmlDoc = new XmlDocument();
xmlDoc.Load("FileFullPath");
var wantedNode = xmlDoc.DocumentElement.GetNodeWithName("name5") // Which can be recursive or iterative

My method signature could be like this:

public XmlNode GetNodeWithName(string nodeNameAttributeValue){
  ... Method content
  return myNode
}

Are there any ease to use method like this?


Solution

  • You can use System.Xml.Linq:

    var item = xmlDoc.Descendants()
               .FirstOrDefault(node => (string)node.Attribute("name") == "name 5")