开发者

Search for nodes by name in XmlDocument

开发者 https://www.devze.com 2022-12-29 21:47 出处:网络
I\'m t开发者_JAVA技巧rying to find a node by name in an XmlDocument with the following code: private XmlNode FindNode(XmlNodeList list, string nodeName)

I'm t开发者_JAVA技巧rying 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?


Why can't you use

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

?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号