tags:

views:

53

answers:

2

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?

+4  A: 

Change this line:

if (node.HasChildNodes) FindNode(node.ChildNodes, nodeName);

to:

if (node.HasChildNodes)
{
    XmlNode nodeFound = FindNode(node.ChildNodes, nodeName);
    if (nodeFound != null)
        return nodeFound;
}

EDITED: the code is more correct now (tested) ;)

digEmAll
Thanks, dude. Kind of stupid that I missed something so simple.
RajenK
Sometimes the more you check the code, the less you succeed in fixing it... :D
digEmAll
One additional question: if I have an XML structure with multiple paths ie:<a> <b> <c/> </b> <d> <e/> </d></a>it only seems to navigate the first tree (to c), but it doesn't find e with the above method. Is this expected behavior with my code?
RajenK
Sorry, I didn't read well your comment. I've edited the post, now it's more correct (and I've tested it too with your sample)
digEmAll
Anyway I still suggest you to check if XPath navigation fits your needs http://support.microsoft.com/kb/308333Or maybe LINQ to XML
digEmAll
+1  A: 

Why can't you use

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

?

Tom W