Search for nodes by name in XmlDocument

2019-03-25 01:54发布

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?

2条回答
我只想做你的唯一
2楼-- · 2019-03-25 02:02

Why can't you use

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

?

查看更多
forever°为你锁心
3楼-- · 2019-03-25 02:18

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) ;)

查看更多
登录 后发表回答