Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for nodes by name in XmlDocument

Tags:

c#

xmldocument

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?

like image 665
RajenK Avatar asked May 09 '10 09:05

RajenK


People also ask

Should I use XDocument or XmlDocument?

XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument . If you're new to both, check out this page that compares the two, and pick which one you like the looks of better.

What's the difference between XmlDocument and XmlReader?

Based on my understanding of the two classes, XmlReader should perform faster in my scenario because it reads through an XML document only once, never storing more than the current node in memory. On the contrary, XmlDocument stores the whole XML file in memory which has some performance overhead.

What is the difference between XmlNode and XmlElement?

Every XmlElement is XmlNode, but not every XmlNode is XmlElement. XmlElement is just one kind of XmlNode. Others are XmlAttribute, XmlText etc. An Element is part of the formal definition of a well-formed XML document, whereas a node is defined as part of the Document Object Model for processing XML documents.

What is node in XML DOM?

According to the XML DOM, everything in an XML document is a node: The entire document is a document node. Every XML element is an element node. The text in the XML elements are text nodes.


1 Answers

Why can't you use

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

?

like image 160
Tom W Avatar answered Oct 05 '22 00:10

Tom W