Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlNode.SelectSingleNode syntax to search within a node in C#

I want to limit my search for a child node to be within the current node I am on. For example, I have the following code:

XmlNodeList myNodes = xmlDoc.DocumentElement.SelectNodes("//Books");
    foreach (XmlNode myNode in myNodes)
    {
         string lastName = "";
         XmlNode lastnameNode = myNode.SelectSingleNode("//LastName");
         if (lastnameNode != null)
         {
              lastName = lastnameNode.InnerText;
         }
    }

I want the LastName element to be searched from within the current myNode inside of the foreach. What is happening is that the found LastName is always from the first node withing myNodes. I don't want to hardcode the exact path for LastName but instead allow it to be flexible as to where inside of myNode it will be found. I would have thought that using SelectSingleNode method on myNode would have limited the search to only be within the xml contents of myNode and not include the parent nodes.

like image 810
user31673 Avatar asked Aug 05 '11 00:08

user31673


People also ask

What is SelectSingleNode c#?

SelectSingleNode(String) Selects the first XmlNode that matches the XPath expression. SelectSingleNode(String, XmlNamespaceManager) Selects the first XmlNode that matches the XPath expression. Any prefixes found in the XPath expression are resolved using the supplied XmlNamespaceManager.

How to Select specific XML node c#?

XPath is used programmatically to evaluate expressions and pick specific nodes in an XML document. To select nodes from XML, use the Evaluate() method. Copy var dealers = document. evaluate("//Dealer", document, null, XPathResult.

What is XmlNodeList?

XmlNode. SelectNodes - Returns an XmlNodeList containing a collection of nodes matching the XPath query. GetElementsByTagName - Returns an XmlNodeList containing a list of all descendant elements that match the specified name. This method is available in both the XmlDocument and XmlElement classes.

What is an XML node?

Node. Everything in an XML document is a node. For example, the entire document is the document node, and every element is an element node. Root node. The topmost node of a tree.


1 Answers

A leading // always starts at the root of the document; use .// to start at the current node and search just its descendants:

XmlNode lastnameNode = myNode.SelectSingleNode(".//LastName");
like image 189
Bradley Grainger Avatar answered Sep 21 '22 19:09

Bradley Grainger