XmlNode.SelectSingleNode语法在C#中的一个节点中搜索 [英] XmlNode.SelectSingleNode syntax to search within a node in C#

查看:1933
本文介绍了XmlNode.SelectSingleNode语法在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;
         }
    }



我想从内搜索的姓氏元素在fo​​reach内部电流MYNODE。正在发生的事情是,发现的姓氏总是从第一个节点withing myNodes。我不想硬编码为名字的确切路径,而是允许其是柔性的,以在那里MYNODE内它会被发现。我本来以为上MYNODE使用selectSingleNode方法会限制搜索只MYNODE的XML内容之内,不包括父节点。

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.

推荐答案

一个领先的 // 总是从文档的根;使用 .// 来开始在当前节点和搜索只是它的后代:

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

这篇关于XmlNode.SelectSingleNode语法在C#中的一个节点中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆