在XML中,SelectNodes方法是用于选择并返回匹配特定XPath表达式的节点集合。SelectNodes方法是XmlNode类的一个成员,因此需要通过一个XmlNode对象来调用该方法。以下是SelectNodes方法的使用方法:
XmlDocument对象,并加载XML文件:XmlDocument xmlDoc = new XmlDocument();xmlDoc.Load("path/to/xml/file.xml");获取要查询的节点:XmlNodeList nodeList = xmlDoc.SelectNodes("XPathExpression");其中,XPathExpression是一个XPath表达式,用于选择要查询的节点。例如,可以使用以下XPath表达式选择所有<book>节点:
XmlNodeList nodeList = xmlDoc.SelectNodes("//book");遍历查询结果:foreach (XmlNode node in nodeList){// 处理每个匹配的节点}以下是一个完整的示例,演示如何使用SelectNodes方法查询XML中的节点:
using System;using System.Xml;class Program{static void Main(){// 加载XML文档XmlDocument xmlDoc = new XmlDocument();xmlDoc.Load("path/to/xml/file.xml");// 选择要查询的节点XmlNodeList nodeList = xmlDoc.SelectNodes("//book");// 遍历查询结果foreach (XmlNode node in nodeList){// 获取节点的属性值string title = node.SelectSingleNode("title").InnerText;string author = node.SelectSingleNode("author").InnerText;string year = node.SelectSingleNode("year").InnerText;// 输出节点的信息Console.WriteLine("Title: " + title);Console.WriteLine("Author: " + author);Console.WriteLine("Year: " + year);Console.WriteLine();}}}在上述示例中,我们加载了一个名为file.xml的XML文件,并使用XPath表达式//book选择了所有<book>节点。然后,我们遍历了这些节点,并输出了每个节点的标题、作者和年份。