添加节点

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

public partial class InsertNode : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(Server.MapPath("~/students.xml"));
        //创建元素<student>  使用CreateElement()方法
        XmlElement newNode = xmlDoc.CreateElement("student");
        //为元素设置属性
        newNode.SetAttribute("id", "004");
        XmlElement newNodeChild = xmlDoc.CreateElement("name");
        //直接使用innerTxt赋值
        newNodeChild.InnerText = "Marry";
        //将子元素<name>追加到<student>元素中作为子元素
        newNode.AppendChild(newNodeChild);

        newNodeChild = xmlDoc.CreateElement("class");
        newNodeChild.InnerText = "G3T14";
        newNode.AppendChild(newNodeChild);

        newNodeChild = xmlDoc.CreateElement("sex");
        newNodeChild.InnerText = "女";
        newNode.AppendChild(newNodeChild);

        newNodeChild = xmlDoc.CreateElement("birth");
        XmlElement newNodeGrand = xmlDoc.CreateElement("year");
        newNodeGrand.InnerText = "1994";
        newNodeChild.AppendChild(newNodeGrand);
        newNodeGrand = xmlDoc.CreateElement("month");
        newNodeGrand.InnerText = "12";
        newNodeChild.AppendChild(newNodeGrand);
        newNodeGrand = xmlDoc.CreateElement("day");
        newNodeGrand.InnerText = "12";
        newNodeChild.AppendChild(newNodeGrand);
        newNode.AppendChild(newNodeChild);
        //创建5个<skill>元素
        newNodeChild = xmlDoc.CreateElement("skill");
        newNodeChild.InnerText = ".Net";
        newNode.AppendChild(newNodeChild);

        newNodeChild = xmlDoc.CreateElement("skill");
        newNodeChild.InnerText = "C#";
        newNode.AppendChild(newNodeChild);

        newNodeChild = xmlDoc.CreateElement("skill");
        newNodeChild.InnerText = "XHML";
        newNode.AppendChild(newNodeChild);

        newNodeChild = xmlDoc.CreateElement("skill");
        newNodeChild.InnerText = "ASP.Net";
        newNode.AppendChild(newNodeChild);

        newNodeChild = xmlDoc.CreateElement("skill");
        newNodeChild.InnerText = "Ajax";
        newNode.AppendChild(newNodeChild);

        //将<student>元素追加到根元素中,作为最后一个子元素
        xmlDoc.DocumentElement.AppendChild(newNode);
        //保存XML文件的修改
        xmlDoc.Save(Server.MapPath("~/students.xml"));
        Response.Write("<script>alert('添加节点完成')</script>");

    }
}

posted @ 2012-04-22 20:26  微笑de『MY』  阅读(237)  评论(0编辑  收藏  举报