我有一个XML文件,格式如下:
<World>
<Country 1>
<City 1>
District 1
District 2
District 3
</City 1>
<City 2>
District 1
District 2
District 3
</City 2>
</Country 1>
<Country 2>
...
</Country n>
</World>
我需要有4个列表框,以便第一个包含国家/地区名称。第二个城市和第三个区。此外,每当我选择父类别时,应选择与父母相关的所有子类别。也就是说,选择国家一应该显示并选择一个国家(但不是地区)的城市。 我还需要更新列表框。同时选择国家1和2应显示国家1和2中的所有城市。
答案 0 :(得分:0)
这是您请求的代码(首先需要在页面上放置3个ListBox项目并连接其SelectedValueChange事件):
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 = "/World/" + country;
var countryElement = nav.SelectSingleNode(xpath);
countryElement.MoveToFirstChild();
var cities = new List<string>();
cities.Add(countryElement.LocalName);
while (countryElement.MoveToNext())
{
cities.Add(countryElement.LocalName);
}
listBox2.DataSource = cities;
BindDistricts(country, cities[0]);
}
protected void BindDistricts(string country, string city)
{
nav.MoveToRoot();
var xpath = "/World/" + country + "/" + city;
var districtElement = nav.SelectSingleNode(xpath);
districtElement.MoveToFirstChild();
var districts = new List<string>();
districts.Add(districtElement.LocalName);
while (districtElement.MoveToNext())
{
districts.Add(districtElement.LocalName);
}
listBox3.DataSource = districts;
}
private void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
BindCities((string)listBox1.SelectedValue);
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
BindDistricts((string)listBox1.SelectedValue, (string)listBox2.SelectedValue);
}
}
}
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>
随意询问您是否有任何问题