xml读写删除

读取xml某节点的某个属性时,则先将xmlnode 转换成 XmlElement。

删除xml某个节点,如果用node.RemoveAll();的话就会留下节点名称,用node.ParentNode.RemoveChild(node);

就可以完全清除了。

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.Text;



namespace web

{

    public partial class Default : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            xmlpath = Server.MapPath(@"xml/fige.xml");

            read();

            save();

            Del();



        }



        public string xmlpath

        {

            get;

            set;

        }



        /// <summary>

        /// 读

        /// </summary>

        private void read()

        {

           

            XmlDocument document = new XmlDocument();

            document.Load(xmlpath);

            XmlNodeList nodelist = document.SelectNodes("xml/table");

            foreach (XmlNode node in nodelist)

            {

                XmlElement xmlelement = (XmlElement)node;

                string tablename = xmlelement.GetAttribute("name");

                XmlNodeList cnodelist = node.SelectNodes("column");

                foreach (XmlNode cnode in cnodelist)

                {

                    XmlElement celement = (XmlElement)cnode;

                    string columnkey = celement.GetAttribute("name");

                    string value = cnode.InnerXml;

                }



            }

        }



        /// <summary>

        /// 写

        /// </summary>

        private void save()

        {

            XmlDocument document = new XmlDocument();

            document.Load(xmlpath);

            XmlNodeList nodelist = document.SelectNodes("xml/table");

            foreach (XmlNode node in nodelist)

            {

                XmlElement xmlelement = (XmlElement)node;

                xmlelement.SetAttribute("name", "我最ae44");

                XmlNodeList cnodelist = node.SelectNodes("column");

                foreach (XmlNode cnode in cnodelist)

                {

                    cnode.InnerXml = "大家都说你知道啊";

                }

                 XmlElement xxxx= document.CreateElement("author");

                 xxxx.InnerXml = "a3dd";

                 node.AppendChild(xxxx);

                



            }

            document.Save(xmlpath);



        }



        /// <summary>

        /// 删除

        /// </summary>

        private void Del()

        {

            XmlDocument document = new XmlDocument();

            document.Load(xmlpath);

            XmlNodeList nodelist = document.SelectNodes("xml/table/author");

            foreach (XmlNode node in nodelist)

            {

                node.RemoveAll();

                node.ParentNode.RemoveChild(node);







            }

            document.Save(xmlpath);

        }



    }

}

你可能感兴趣的:(xml)