How to select node using XPathNavigator.SelectSingleNode (xpath string)?

I have this xml file "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> 

In the BindCities method (country string), I try to get to the country () element, but the nav variable does not change its value to the country element after running the code, it just remains in the last place. I tried many methods but nothing worked.

 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; } } } 

What code do I need to access a country element using the XPathNavigator?

Thank you for your responses!

+4
source share
1 answer

The correct use of the SelectSingleNode method is as follows:

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

All Articles