Search for nodes by name in XmlDocument

RajenK picture RajenK · May 9, 2010 · Viewed 32.6k times · Source

I'm trying to find a node by name in an XmlDocument with the following code:

private XmlNode FindNode(XmlNodeList list, string nodeName)
{
    if (list.Count > 0)
    {
        foreach (XmlNode node in list)
        {
            if (node.Name.Equals(nodeName)) return node;
            if (node.HasChildNodes) FindNode(node.ChildNodes, nodeName);
        }
    }
    return null;
}

I call the function with:

FindNode(xmlDocument.ChildNodes, "somestring");

For some reason it always returns null and I'm not really sure why. Can someone help me out with this?

Answer

Tom W picture Tom W · May 9, 2010

Why can't you use

Node.SelectSingleNode(".//" + nodeName)

?