XmlNode.SelectNodes 方法 (String)

本文介绍如何使用XPath表达式选择XML文档中的节点集合,并提供了一个通过作者姓名筛选书籍价格的示例。

选择匹配 XPath 表达式的节点列表。

[VisualBasic]
Overloads Public Function SelectNodes( _
   ByVal xpath As String _
) As XmlNodeList
[C#]
public XmlNodeList SelectNodes(
   string xpath
);
[C++]
public: XmlNodeList* SelectNodes(
   String* xpath
);
[JScript]
public function SelectNodes(
   xpath : String
) : XmlNodeList;
参数
xpath
XPath 表达式。
返回值

一个 XmlNodeList,包含匹配 XPath 查询的节点集合。

异常
异常类型条件
XPathExceptionXPath 表达式包含前缀。
备注

如果 XPath 表达式需要命名空间解析,必须使用接受 XmlNamespaceManager 作为参数的 SelectNodes 重载。XmlNamespaceManager 用于解析命名空间。

注意如果 XPath 表达式不包含前缀,则假定命名空间 URI 为空命名空间。如果 XML 包含默认命名空间,则您仍必须使用 XmlNamespaceManager 并向其添加前缀和命名空间 URI,否则将得不到任何选定的节点。

该方法是文档对象模型 (DOM) 的 Microsoft 扩展。

示例

[VisualBasic,C#,C++] 下面的示例更改所有 Jane Austen 写的书的价格。

[VisualBasic] 
Imports System
Imports System.IO
Imports System.Xml

public class Sample

  public shared sub Main()

    'Create the XmlDocument.
    Dim doc as XmlDocument = new XmlDocument()
    doc.Load("booksort.xml")
           
    Dim book as XmlNode
    Dim nodeList as XmlNodeList 
    Dim root as XmlNode = doc.DocumentElement

    nodeList=root.SelectNodes("descendant::book[author/last-name='Austen']")
 
    'Change the price on the books.
    for each book in nodeList      
      book.LastChild.InnerText="15.95"
    next 

    Console.WriteLine("Display the modified XML document....")
    doc.Save(Console.Out)
    
  end sub
end class

[C#] 
using System;
using System.IO;
using System.Xml;

public class Sample {

  public static void Main() {

    XmlDocument doc = new XmlDocument();
    doc.Load("booksort.xml");

    XmlNodeList nodeList;
    XmlNode root = doc.DocumentElement;

    nodeList=root.SelectNodes("descendant::book[author/last-name='Austen']");
 
    //Change the price on the books.
    foreach (XmlNode book in nodeList)
    {
      book.LastChild.InnerText="15.95";
    }

    Console.WriteLine("Display the modified XML document....");
    doc.Save(Console.Out);
    
  }
}

[C++] 
#using 
 
#using 
 
using namespace System;
using namespace System::IO;
using namespace System::Xml;

int main()
{
    XmlDocument* doc = new XmlDocument();
    doc->Load(S"booksort.xml");

    XmlNodeList* nodeList;
    XmlNode* root = doc->DocumentElement;

    nodeList=root->SelectNodes(S"descendant::book[author/last-name='Austen']");
 
    //Change the price on the books.
    System::Collections::IEnumerator* myEnum = nodeList->GetEnumerator();
    while (myEnum->MoveNext())
    {
        XmlNode* book = __try_cast(myEnum->Current);
        book->LastChild->InnerText=S"15.95";
    }

    Console::WriteLine(S"Display the modified XML document....");
    doc->Save(Console::Out);
}

[VisualBasic,C#,C++] 该示例使用文件 booksort.xml 作为输入。

 

 

 
  
 
    
    
 
      
 Jane
      
 Austen
    
    
 24.95
  
  
 
    
    
 
      
 Margaret
      
 Atwood
    
    
 29.95
  
  
 
    
    
 
      
 Jane
      
 Austen
    
    
 19.95
  
  
 
    
    
 
      
 Jane
      
 Austen
    
    
 19.95
  

[JScript] 没有可用于 JScript 的示例。若要查看 Visual Basic、C# 或 C++ 示例,请单击页左上角的“语言筛选器”

/* * 由SharpDevelop创建。 * 用户: Administrator * 日期: 03/13/2014 * 时间: 21:41 * * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件 * */ using System; using System.Xml; using System.Collections; using demo_chechBox.baseMain; using System.Text; namespace demo_chechBox.tool { /*解析城市xml*/ public class AnalyticalXml { public static string citiesXmlName = "../../xml/comboBox/Cities.xml"; public static string districtsXmlName = "../../xml/comboBox/Districts.xml"; public static string userXmlName = "../../xml/dataSource/user.xml"; public AnalyticalXml() { } /*获取所有城市*/ public static IList findAllCity() { IList array = new ArrayList(); XmlDocument xmlDoc = getXmlDocument(citiesXmlName); XmlNodeList xnlList = xmlDoc.SelectNodes("Cities/City"); foreach(XmlNode x in xnlList) { array.Add(x.InnerText); } return array; } /**根据城市查询区*/ public static IList findAllDistricts(string city) { IList array = new ArrayList(); //获取城市ID XmlElement xe = getElementByCity(city); string cityId = xe.GetAttribute("ID"); //查询城市下边的子区 XmlDocument xmldoc = getXmlDocument(districtsXmlName); XmlNodeList nodeList = xmldoc.SelectNodes("Districts/District[@CID='"+cityId+"']"); foreach (XmlNode xn in nodeList) { array.Add(xn.InnerText); } return array; } /**以username为条件查询指定User*/ public static User getUser(string username) { XmlDocument xmldoc = getXmlDocument(userXmlName); XmlElement xe = (XmlElement)xmldoc.SelectNodes("users/user[@username='"+username+"']")[0]; if(xe!=null) { User user = new User(); user.setPassword(xe.GetAttribute("password")); user.setUsername(xe.GetAttribute("username")); user.setAddress(xe.GetAttribute("address")); user.setFileName(xe.GetAttribute("fileName")); user.setHobby(xe.GetAttribute("hobby")); user.setPhoto(xe.GetAttribute("photo")); user.setRemarks(xe.GetAttribute("remarks")); user.setBirtday(xe.GetAttribute("birtday")); user.setGender(xe.GetAttribute("gender")); return user; } return null; } public static XmlElement getElementByCity(string city) { XmlDocument xmlDoc = getXmlDocument(citiesXmlName); XmlNode xmlde = xmlDoc.SelectNodes("Cities/City[@CityName='"+city+"']")[0]; XmlElement xe = xmlde as XmlElement; return xe; } //保存user public static void saveUser(User user) { XmlDocument xmldoc = getXmlDocument(userXmlName); XmlNode root = xmldoc.DocumentElement; //创建新节点 XmlElement newChild = xmldoc.CreateElement("user"); newChild.SetAttribute("guid",user.Guid); newChild.SetAttribute("username",user.getUsername()); newChild.SetAttribute("password",user.getPassword()); newChild.SetAttribute("gender",user.getGender()); newChild.SetAttribute("birtday",user.getBirtday()); newChild.SetAttribute("hobby",user.getHobby()); newChild.SetAttribute("address",user.getAddress()); newChild.SetAttribute("photo",user.getPhoto()); newChild.SetAttribute("remarks",user.getRemarks()); newChild.SetAttribute("fileName",user.getFileName()); //添加users的最后一个子级节点后面 //XmlNode refChild = xmldoc.SelectNodes("users")[0]; XmlNode child = root.LastChild; if(child!=null) { root.InsertAfter(newChild,root.LastChild); } else { root.AppendChild(newChild); } //保存 XmlTextWriter xmlWriter = new XmlTextWriter(userXmlName,Encoding.GetEncoding("utf-8")); xmlWriter.Formatting = Formatting.Indented; xmldoc.Save(xmlWriter); xmlWriter.Close(); } public static XmlDocument getXmlDocument(string xmlName) { XmlDocument xmldoc = new XmlDocument(); try { xmldoc.Load(xmlName); } catch(Exception ex) { throw new OverflowException("找不到"+xmlName+"文件,抛出"+ex.Message); } return xmldoc; } } } 逐行解释代码并解释system是什么意思
最新发布
09-25
using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; // 必须添加这个命名空间引用 using System.Configuration; using System.Xml; namespace _7 { public partial class Form1 : Form { private List<string> recentFiles = new List<string>(); private const int MaxRecentFiles = 5; private string currentFilePath = null; // 添加当前文件路径字段 public Form1() { InitializeComponent(); this.Controls.Add(txtContent); LoadRecentFiles(); // 加载历史记录 } // 保存历史记录到XML文件 private void SaveRecentFiles() { string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); string appFolder = Path.Combine(appDataPath, "YourAppName"); string configPath = Path.Combine(appFolder, "config.xml"); // 确保目录存在 Directory.CreateDirectory(appFolder); using (XmlWriter writer = XmlWriter.Create(configPath)) { writer.WriteStartDocument(); writer.WriteStartElement("Configuration"); writer.WriteStartElement("RecentFiles"); foreach (string file in recentFiles) { writer.WriteElementString("File", file); } writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); } } // 从XML文件加载历史记录 private void LoadRecentFiles() { string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); string configPath = Path.Combine(appDataPath, "YourAppName", "config.xml"); if (File.Exists(configPath)) { try { XmlDocument doc = new XmlDocument(); doc.Load(configPath); recentFiles.Clear(); XmlNodeList fileNodes = doc.SelectNodes("/Configuration/RecentFiles/File"); if (fileNodes != null) { foreach (XmlNode node in fileNodes) { if (!string.IsNullOrEmpty(node.InnerText)) { recentFiles.Add(node.InnerText); } } } } catch (Exception ex) { MessageBox.Show($"加载历史记录失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } UpdateRecentFilesMenu(); } // 更新最近文件菜单 private void UpdateRecentFilesMenu() { // 确保菜单项存在 if (menuRecentFiles == null) { menuRecentFiles = new ToolStripMenuItem("最近文件"); menuFile.DropDownItems.Add(menuRecentFiles); } menuRecentFiles.DropDownItems.Clear(); foreach (string file in recentFiles) { ToolStripMenuItem item = new ToolStripMenuItem(Path.GetFileName(file)); item.Tag = file; item.Click += RecentFile_Click; menuRecentFiles.DropDownItems.Add(item); } // 添加清除历史选项 if (recentFiles.Count > 0) { menuRecentFiles.DropDownItems.Add(new ToolStripSeparator()); ToolStripMenuItem clearItem = new ToolStripMenuItem("清除历史记录"); clearItem.Click += (s, e) => { recentFiles.Clear(); SaveRecentFiles(); UpdateRecentFilesMenu(); }; menuRecentFiles.DropDownItems.Add(clearItem); } } // 从设置加载历史记录 private void LoadRecentFiles() { string configPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "YourAppName", "config.xml"); if (File.Exists(configPath)) { XmlDocument doc = new XmlDocument(); doc.Load(configPath); recentFiles.Clear(); foreach (XmlNode node in doc.SelectNodes("/Configuration/RecentFiles/File")) { recentFiles.Add(node.InnerText); } } } private void txtInput_TextChanged(object sender, EventArgs e) { } private void 编辑ToolStripMenuItem_Click(object sender, EventArgs e) { } private void btnSave_Click_1(object sender, EventArgs e) { if (currentFilePath != null && File.Exists(currentFilePath)) { // 直接保存到当前文件 SaveToFile(currentFilePath); } else { // 弹出保存对话框 SaveWithDialog(); } } // 使用对话框保存 private void SaveWithDialog() { using (SaveFileDialog saveDialog = new SaveFileDialog()) { saveDialog.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*"; saveDialog.FilterIndex = 1; if (saveDialog.ShowDialog() == DialogResult.OK) { currentFilePath = saveDialog.FileName; SaveToFile(currentFilePath); AddToRecentFiles(currentFilePath); } } } // 实际保存文件的方法 private void SaveToFile(string path) { try { File.WriteAllText(path, txtContent.Text); MessageBox.Show($"文件已保存至:\n{path}", "保存成功"); UpdateRecentFilesMenu(); } catch (Exception ex) { MessageBox.Show($"保存失败:\n{ex.Message}", "错误"); } } private void btnOpen_Click(object sender, EventArgs e) { using (OpenFileDialog openDialog = new OpenFileDialog()) { openDialog.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*"; openDialog.FilterIndex = 1; if (openDialog.ShowDialog() == DialogResult.OK) { OpenFile(openDialog.FileName); } } } // 打开文件的方法 private void OpenFile(string path) { try { txtContent.Text = File.ReadAllText(path); currentFilePath = path; AddToRecentFiles(path); UpdateRecentFilesMenu(); MessageBox.Show($"已打开文件:\n{path}", "打开成功"); } catch (Exception ex) { MessageBox.Show($"打开失败:\n{ex.Message}", "错误"); } } // 添加到最近文件列表 private void AddToRecentFiles(string path) { // 如果已存在则移除 if (recentFiles.Contains(path)) { recentFiles.Remove(path); } // 添加到列表顶部 recentFiles.Insert(0, path); // 限制历史记录数量 if (recentFiles.Count > MaxRecentFiles) { recentFiles.RemoveAt(recentFiles.Count - 1); } // 保存到设置 SaveRecentFiles(); } // 更新最近文件菜单 private void UpdateRecentFilesMenu() { menuRecentFiles.DropDownItems.Clear(); foreach (string file in recentFiles) { ToolStripMenuItem item = new ToolStripMenuItem(Path.GetFileName(file)); item.Tag = file; item.Click += RecentFile_Click; menuRecentFiles.DropDownItems.Add(item); } // 添加清除历史选项 menuRecentFiles.DropDownItems.Add(new ToolStripSeparator()); ToolStripMenuItem clearItem = new ToolStripMenuItem("清除历史记录"); clearItem.Click += (s, e) => { recentFiles.Clear(); SaveRecentFiles(); UpdateRecentFilesMenu(); }; menuRecentFiles.DropDownItems.Add(clearItem); } private void menuRecentFiles_Click(object sender, EventArgs e) { if (sender is ToolStripMenuItem item && item.Tag != null) { string path = item.Tag.ToString(); if (File.Exists(path)) { OpenFile(path); } else { MessageBox.Show("文件不存在或已被移动", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); recentFiles.Remove(path); SaveRecentFiles(); UpdateRecentFilesMenu(); } } } // 使用对话框保存 private void SaveWithDialog() { using (SaveFileDialog saveDialog = new SaveFileDialog()) { saveDialog.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*"; saveDialog.FilterIndex = 1; if (saveDialog.ShowDialog() == DialogResult.OK) { currentFilePath = saveDialog.FileName; SaveToFile(currentFilePath); AddToRecentFiles(currentFilePath); } } } // 实际保存文件的方法 private void SaveToFile(string path) { try { File.WriteAllText(path, txtContent.Text); MessageBox.Show($"文件已保存至:\n{path}", "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information); UpdateRecentFilesMenu(); } catch (Exception ex) { MessageBox.Show($"保存失败:\n{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } // 打开文件的方法 private void OpenFile(string path) { try { txtContent.Text = File.ReadAllText(path); currentFilePath = path; AddToRecentFiles(path); MessageBox.Show($"已打开文件:\n{path}", "打开成功", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show($"打开失败:\n{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } // 添加到最近文件列表 private void AddToRecentFiles(string path) { // 如果已存在则移除 if (recentFiles.Contains(path)) { recentFiles.Remove(path); } // 添加到列表顶部 recentFiles.Insert(0, path); // 限制历史记录数量 if (recentFiles.Count > MaxRecentFiles) { recentFiles.RemoveAt(recentFiles.Count - 1); } // 保存到设置 SaveRecentFiles(); } private void menuSave_Click(object sender, EventArgs e) { if (currentFilePath != null && File.Exists(currentFilePath)) { SaveToFile(currentFilePath); } else { SaveWithDialog(); } } private void menuOpen_Click(object sender, EventArgs e) { using (OpenFileDialog openDialog = new OpenFileDialog()) { openDialog.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*"; openDialog.FilterIndex = 1; if (openDialog.ShowDialog() == DialogResult.OK) { OpenFile(openDialog.FileName); } } } } } LoadRecentFiles(); // 加载历史记录有二义性
07-03
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值