14

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.

user31673
  • 13,245
  • 12
  • 58
  • 96

2 Answers2

34

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");
Bradley Grainger
  • 27,458
  • 4
  • 91
  • 108
  • The "." worked great. Do you know where that syntax can be found? I have searched for this kind of information and found the "//" but not the "." I am thinking there is other syntax that I can use. – user31673 Aug 05 '11 at 00:12
  • Updated link to XPath syntax that @ibo.ezhe mentioned: https://www.w3schools.com/xml/xpath_syntax.asp – PolyTekPatrick Jun 15 '17 at 02:50
1

Actually, the problem relates to XPath. XPath syntax // means you select nodes in the document from the current node that match the selection no matter where they are

so all you need is to change it to

myNode.SelectSingleNode(".LastName")
wezzix
  • 1,984
  • 1
  • 19
  • 18
maxk
  • 642
  • 1
  • 9
  • 21
  • This will only find it one level down. The OP said he wanted it to find it anywhere within the subtree. – Kyle W Aug 05 '11 at 00:13