第1章 ASP.NET XML与JSON

DOM树节点的五种类型:(下面以一个示例来演示这几种类型)

<?xml version="1.0" encoding="ISO-8859-1"?>    //注释节点(Comments)
<bookstore>    //元素根节点/文档节点(Docment)
    <book category="children">    
    <title lang="en">Harry Potter</title>
    <author>Jk.Rowling</author>
    <year>2005</year>
    <price>29.99</price>
    </book>
</bookstore>
//book,title,author,year,price都是元素节点(Element). 
//category,lang是属性节点(Attribute). 
//Harry Potter,Jk.Rowling,2005,29.99是文本节点(Text)
//Document与Element大致相同,但在具体用法上会有些不一样

DOM常用对象:
1.XmlNode:用于创建DOM树中的节点(以下例举其中几个属性和方法)
 ChildNodes:获取节点中所有子节点的XmlNodeList,若没有子节点则返回一个空列表.
 NodeType:返回当前节点的类型
 FirstChild:获取当前节点的第一个子节点.
 Value:获取或设置节点的值.
 Name:设置名称. 
 AppendChild():该方法用于把参数添加到节点的末尾
 Clone():复制所有的节点和属性,等价于CloneNode(true).
 InsertBefore():将新节点插入引用节点的前面,与InsertAfter()方法相反.
 PrependChild():将新节点添加到引用节点的子节点列表的开头.
 RemoveChild():删除指定的节点.
 ReplaceChild():替换一个子节点.

2.XmlDocument:派生自XmlNode类,用于创建一个Xml文档对象,也可以创建新节点.
 DocumentElement:获取树的根.
 CreateAttribute():创建一个属性(XmlAttribute)节点.
 CreateNode():创建一个元素(XmlElement)节点.
 Load():加载一个XML文档,并解析它.
 Save():把XML文档保存在指定的位置上.

3.XmlElement:派生自XmlNode类,创建XML文档中的元素节点
 SetAttribute():设置属性的值
 SetAttributeNode():添加一个新的XmlAttribute.

4.XmlAttribute:也派生自XmlNode类,创建Xml文档中的属性节点


DOM综合使用实例存储员工信息:(用XMl文件存储员工信息,该xml文件的格式如下)

<?xml version="1.0" encoding="utf-8"?>
<company name="公司名称">
    <department name="部门1名称">
        <employee name="员工1姓名" age="年龄" sex="性别" telephone="电话" email="电子邮箱"/>
    </department>
    <department name="部门2名称">
        <employee name="员工2姓名" age="年龄" sex="性别" telephone="电话" email="电子邮箱"/>
    </department>
</company>

该实例解析如下:
页面设计要求:新建一个aspx页面,3个button按钮:添加部门按钮,添加员工按钮,查看员工按钮.1个MultiView(多视图)控件,此控件里包含4个View控件,1个用于添加公司名称,1个用于添加部门,1个用于添加员工,1个用于显示员工信息,同时通过设置MultiView控件的ActiveViewIndex属性来指定当前显示的View控件.
先写一个员工实体类:

public class Employee
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Sex { get; set; }
        public string Email { get; set; }
        public string Telephone { get; set; }
        public string Department { get; set; }
    }

页面后台代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.IO;

namespace LianXi
{
    public partial class Manage : System.Web.UI.Page
    {
      
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string fileName = Server.MapPath(@"~\data.xml");
                if (!File.Exists(fileName))    //判断文件是否存在
                {
                    this.MultiView1.ActiveViewIndex = 0;    //设置MultiView1里显示第一个View控件
                }
                else    
                { 
                    //若文件存在,则用Xml读取文件
                    XmlDocument doc = new XmlDocument();
                    doc.Load(fileName);
                    XmlNode root = doc.DocumentElement;
                    string info = "";
                    foreach (XmlNode item in root.ChildNodes)
                    {
                        foreach (XmlNode itemson in item.ChildNodes)
                        {
                            foreach (XmlNode son in itemson.Attributes)
                            {
                                info += son.Value;
                            }
                        }
                        info += " <br/>";
                    }
                    Response.Write(info);
                }
            }
        }

        //创建一个元素节点,添加公司
        protected void btnInit_Click(object sender, EventArgs e)
        {
            string companyname = this.txtCompany.Text;
            XmlDocument doc = new XmlDocument();
            XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0","utf-8",null);
            XmlElement root = doc.CreateElement("Company");
            root.SetAttribute("name", companyname);
            root.IsEmpty = false;
            doc.AppendChild(declaration);
            doc.AppendChild(root);
            string fileName = Server.MapPath(@"~\data.xml");
            doc.Save(fileName);
            txtCompany.Text = "";
            
        }

        //添加部门
        protected void btnDeparment_Click(object sender, EventArgs e)
        {
            string deparmentName = this.txtDeparment.Text;
            XmlDocument doc = new XmlDocument();
            string fileName = Server.MapPath(@"~\data.xml");
            doc.Load(fileName);

            XmlElement department = doc.CreateElement("deparment");
            department.SetAttribute("name", deparmentName);
            doc.DocumentElement.AppendChild(department);
            doc.Save(fileName);
            doc.DocumentElement.AppendChild(department);
            txtDeparment.Text = "";
        }

        protected void btnAddDmt_Click(object sender, EventArgs e)
        {
           
            this.MultiView1.ActiveViewIndex = 1;
        }

        protected void btnAddRen_Click(object sender, EventArgs e)
        {
            ddlDeparment.Items.Clear();
            this.MultiView1.ActiveViewIndex = 2;
            ShowDepartment();
        }

        //绑定部门名称
        private void ShowDepartment()
        {
            XmlDocument doc = new XmlDocument();
            string fileName = Server.MapPath(@"~\data.xml");
            doc.Load(fileName);

            XmlNodeList lst = doc.DocumentElement.ChildNodes;

            foreach (XmlNode node in lst)
            {
                this.ddlDeparment.Items.Add(node.Attributes["name"].Value);
            }

        }

    //添加员工信息
        protected void btnAddYuan_Click(object sender, EventArgs e)
        {
            int index = this.ddlDeparment.SelectedIndex;

            XmlDocument doc = new XmlDocument();
            string fileName = Server.MapPath(@"~\data.xml");
            doc.Load(fileName);

            XmlElement emp = doc.CreateElement("employee");
            emp.SetAttribute("name", txtName.Text.ToString());
            emp.SetAttribute("age", txtAge.Text.ToString());
            emp.SetAttribute("sex", ddlSex.Text.ToString());
            emp.SetAttribute("email", txtEmail.Text.ToString());
            emp.SetAttribute("phone", txtPhone.Text.ToString());

            doc.DocumentElement.ChildNodes[index].AppendChild(emp);
            doc.Save(fileName);
            doc.DocumentElement.ChildNodes[index].AppendChild(emp);
          

            txtName.Text = "";
            txtAge.Text = "";
            txtEmail.Text = "";
            txtPhone.Text = "";

        }

        protected void btnSelect_Click(object sender, EventArgs e)
        {
            this.MultiView1.ActiveViewIndex = 3;
            ShowEmployee();
        }

        //显示所有员工
        private void ShowEmployee()
        {
            XmlDocument doc = new XmlDocument();
            string fileName = Server.MapPath(@"~\data.xml");
            doc.Load(fileName);

            List<Employee> emplst = new List<Employee>();
            XmlNodeList lst = doc.DocumentElement.ChildNodes;
            //XmlNodeList nodelist = doc.GetElementsByTagName("");
            foreach (XmlNode departmentNode in lst)
            {
                foreach (XmlNode empNode in departmentNode.ChildNodes)
                {
                    Employee emp = new Employee();
                    emp.Name=empNode.Attributes["name"].Value;
                    emp.Age=Convert.ToInt32(empNode.Attributes["age"].Value);
                    emp.Sex=empNode.Attributes["sex"].Value;
                    emp.Telephone = empNode.Attributes["phone"].Value;
                    emp.Email=empNode.Attributes["email"].Value;
                    emp.Department=departmentNode.Attributes["name"].Value;
                    emplst.Add(emp);
                }
            }
            this.ListView1.DataSource = emplst;
            this.ListView1.DataBind();
        }
    }
}
View Code

 

posted @ 2013-12-22 12:09  mmww  阅读(116)  评论(0)    收藏  举报