c# – 如何使用XPathNavigator.SelectSingleNode(字符串xpath)选择节点?
作者:互联网
我有这个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(字符串国家)我试图到达country元素()但是nav变量在运行代码后没有将它的值更改为country元素,它只是停留在最后一个位置.我尝试了很多方法,但没有任何效果.
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;
}
}
}
使用nav XPathNavigator到达country元素需要什么代码?
谢谢你的回复!
解决方法:
正确使用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
}
标签:c,select,winforms,xpath,xpathnavigator 来源: https://codeday.me/bug/20190621/1253671.html