居委会试题(解析xml文件)

    xiaoxiao2021-03-25  70

    xml文件

    <?xml version="1.0" encoding="utf-8" ?> <root name="石牌街道"> <juwei name="瑞华居委"> <jianzhu smid="6" name="瑞华花园1栋"> <fjname>101室</fjname> <fjname>102室</fjname> </jianzhu> <jianzhu smid="7" name="瑞华花园2栋"> <fjname>101室</fjname> <fjname>102室</fjname> </jianzhu> </juwei> <juwei name="金帝居委"> <jianzhu smid="4" name="金帝花园1栋"> <fjname>101室</fjname> <fjname>102室</fjname> </jianzhu> </juwei> <juwei name="朝阳居委"> <jianzhu smid="5" name="朝阳花园1栋"> <fjname>101室</fjname> <fjname>102室</fjname> </jianzhu> </juwei> </root>

    解析xml

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; namespace 居委会 { public partial class Main : Form { public Main() { InitializeComponent(); } public void Show() { XmlDocument XmlDoc = new XmlDocument(); //读取相对路径下的xml文件 XmlDoc.Load("Address.xml"); //获取根节点 XmlNode xmlnode = XmlDoc.DocumentElement; //创建一个树节点 TreeNode JieDaoNodes = new TreeNode(); //将xml根节点的name值储存到树节点的text JieDaoNodes.Text = xmlnode.Attributes["name"].InnerText; //将jiedaoNodes树节点绑定到treeView1的根节点 treeView1.Nodes.Add(JieDaoNodes); //声明一个树节点 TreeNode juweiNodes = null; foreach (XmlNode juwei in xmlnode.ChildNodes) { //初始化树节点 juweiNodes = new TreeNode(); //将juwei的name值保存到juweiNodes树节点的text juweiNodes.Text = juwei.Attributes["name"].InnerText; TreeNode DongNodes = null; foreach (XmlNode Dong in juwei.ChildNodes) { //初始化树节点 DongNodes = new TreeNode (); //将Dong的name值保存到DongNodes树节点的text DongNodes.Text = Dong.Attributes["name"].InnerText; ; TreeNode HaoNodes = null; foreach (XmlNode Hao in Dong.ChildNodes) { //初始化树节点 HaoNodes = new TreeNode(); //将获取到Hao中的值保存到HaoNodes树节点的text HaoNodes.Text = Hao.InnerText; //HaoNodes树节点绑定到DongNodes的子节点 DongNodes.Nodes.Add(HaoNodes); } //将DongNodes树节点绑定到JuWeiNodes的子节点 juweiNodes.Nodes.Add(DongNodes); } //将juweiNodes树节点绑定到JieDaoNodes的子节点 JieDaoNodes.Nodes.Add(juweiNodes); } } private void Main_Load(object sender, EventArgs e) { Show(); } private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { //获取选中的节点 TreeNode node=treeView1.SelectedNode; if (node==null) { return; } //只能选取深度为3的节点 if (node.Level!=3) { return; } //获取深度为0的节点的text this.txtStreet.Text = treeView1.Nodes[0].Text; //获取所选节点的父节点的父节点的text this.txtJuWei.Text = node.Parent.Parent.Text; //获取所选节点的父节点的text this.txtBudingNO.Text = node.Parent.Text; //获取所选节点的text this.txtRoomNO.Text = node.Text; } } }
    转载请注明原文地址: https://ju.6miu.com/read-34819.html

    最新回复(0)