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

谁说胖子不能爱 提交于 2019-12-18 14:54:15

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/6950032/xmlnode-selectsinglenode-syntax-to-search-within-a-node-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!