如何使用XPathNavigator选择节点.SelectSingleNode(字符串xpath)

本文关键字:字符串 xpath SelectSingleNode 节点 何使用 XPathNavigator 选择 | 更新日期: 2023-09-27 18:04:32

我有这个xml文件"target.xml":

<World>
  <Nkvavn>
    <Rcltwkb>
      <Pjwrgsik />
      <Nemscmll />
      <Fnauarnbvw />
      <Egqpcerhjgq />
      <Olyhryyxi />
      <Vvlhtiee />
      <Wlsfhmv />
    </Rcltwkb>
    <Xudbhnakjb>
      <Cwxjtkteuji />
      <Fbtcvf />
      <Uviaceinhl />
    </Xudbhnakjb>
    <Kgujcymilwr>
      <Nlbvgtwoejo />
      <Tvufkvmryybh />
      <Xtomstcenmp />
      <Mhnngf />
      <Fjidqdbafxun />
    </Kgujcymilwr>
    <Taiyiclo>
      <Fiecxoxeste />
      <Loqxjq />
      <Vfsxfilxofe />
      <Hroctladlht />
    </Taiyiclo>
  </Nkvavn>
  <Tfrosh>
    <Tuqomkytlp>
      <Oyvivlvminhn />
      <Qeypvfgul />
      <Mbapjl />
    </Tuqomkytlp>
    <Rvxumtj>
      <Gkvigncdvgy />
      <Okcddyi />
      <Vvmacul />
    </Rvxumtj>
    <Pdjpgexuyc>
      <Yvsdmbckurju />
      <Bvkxvg />
      <Clmrvjwk />
      <Hdafjhydj />
      <Asauxtnoe />
      <Mwcviwmi />
    </Pdjpgexuyc>
  </Tfrosh>
</World>

在方法BindCities(字符串国家)我试图得到国家元素(),但nav变量不改变它的值运行代码后的国家元素,它只是停留在最后一个位置。我试了很多方法,但都不管用。

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
namespace MultipleBoundListBox
{
    public partial class Form1 : Form
    {
        private static XmlDocument xmlDoc;
        private static XPathNavigator nav;
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            xmlDoc = new XmlDocument();
            xmlDoc.Load(@"target.xml");
            nav = xmlDoc.DocumentElement.CreateNavigator();
            nav.MoveToFirstChild();
            var countries = new List<string>();
            countries.Add(nav.LocalName);
            while (nav.MoveToNext())
            {
                countries.Add(nav.LocalName);
            }
            listBox1.DataSource = countries;
            BindCities(countries[0]);
        }
        protected void BindCities(string country)
        {
            nav.MoveToRoot();
            var xpath = "//" + country;
            nav.SelectSingleNode(xpath);
            nav.MoveToFirstChild();
            var cities = new List<string>();
            cities.Add(nav.LocalName);
            while (nav.MoveToNext())
            {
                cities.Add(nav.LocalName);
            }
            listBox2.DataSource = cities;
        }
    }
}

我需要什么代码与导航XPathNavigator到达国家元素?

谢谢你的回复!

如何使用XPathNavigator选择节点.SelectSingleNode(字符串xpath)

SelectSingleNode方法的正确使用方法如下:

XPathNavigator node = nav.SelectSingleNode(xpath);
if (node != null) {
  // now access properties of node here e.g. node.LocalName
}
else {
  // if needed handle case that xpath did not select anything
}