现在的位置: 首页 > 综合 > 正文

xml + asp.net 实现 xml数据读取到 treeview

2014年01月10日 ⁄ 综合 ⁄ 共 2061字 ⁄ 字号 评论关闭

页面后台代码:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Person : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //  tvPerson
        if (!Page.IsPostBack)
        {
            System.Xml.XmlDocument document =
                new System.Xml.XmlDataDocument();
            document.Load(Server.MapPath("Person.xml"));

            populateTreeControl(document.DocumentElement,
            this.tvPerson.Nodes);
        }       
    }

    private void populateTreeControl(
        System.Xml.XmlNode document, System.Web.UI.WebControls.TreeNodeCollection nodes)
       // System.Windows.Forms.TreeNodeCollection nodes)
        {
            foreach (System.Xml.XmlNode node in
            document.ChildNodes)
            {
                // If the element has a value, display it;
                // otherwise display the first attribute
                // (if there is one) or the element name
                // (if there isn't)

                string text = (node.Value != null ? node.Value :
                (node.Attributes != null &&
                node.Attributes.Count > 0) ?
                node.Attributes[0].Value : node.Name);
                TreeNode new_child = new TreeNode(text);
                nodes.Add(new_child);
                populateTreeControl(node, new_child.ChildNodes);           
           }
    }
}

测试xml

<?xml version="1.0" encoding="utf-8" ?>
<addressbook>
  <contacts id="Contacts">
    <contact id="Alex">
      <email id="popmail">
        someone@some_pop_mail.net
      </email>
      <city>Edinburgh</city>
      <country>United Kingdom</country>
    </contact>
    <contact id="Rebekah">
      <email id="webmail">
        someone@some_web_mail.net
      </email>
      <city>Papakura</city>
      <country>New Zealand</country>
    </contact>
    <contact id="Justin">
      <email id="webmail">
        someone_else@some_web_mail.com
      </email>
      <city>Muriwai</city>
      <country>New Zealand</country>
    </contact>
  </contacts>
</addressbook>

 

抱歉!评论已关闭.