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?
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.
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.
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.
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.
Why can't you use
Node.SelectSingleNode(".//" + nodeName)
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With