XML_操作

//加载

protected void Page_Load(object sender, EventArgs e)
        {
            string filePath = Server.MapPath("~/xml/addressList.xml");
            if (!Page.IsPostBack)
            {
                if (!File.Exists(filePath))
                {
                    CreteXml();
                }
                else
                {
                    ReadXml();
                }
            }
        }

//创建

private void CreteXml()
        {
            string filePath = Server.MapPath("~/xml/addressList.xml");
            XmlDocument doc = new XmlDocument();
            XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0","utf-8","");
            XmlElement root = doc.CreateElement("addressList");
            root.IsEmpty = false;
            XmlAttribute createTime = doc.CreateAttribute("createTime");
            createTime.Value = DateTime.Now.ToShortDateString();
            root.Attributes.Append(createTime);

            doc.AppendChild(declaration);
            doc.AppendChild(root);

            doc.Save(filePath);
        }

//读取

        private void ReadXml()
        {
            List<LinkMan> lst = new List<LinkMan>();
            XmlDocument doc = new XmlDocument();
            //加载xml
            doc.Load(Server.MapPath("~/xml/addressList.xml"));
            XmlNodeList nodeList = doc.GetElementsByTagName("linkman");

            foreach (XmlNode node in nodeList)
            {
                LinkMan linkMan = new LinkMan();
                if (node.Attributes["name"]!=null)
                {
                    linkMan.Name = node.Attributes["name"].Value;
                }
                lst.Add(linkMan);
            }

            this.GridView1.DataSource = lst;
            this.GridView1.DataBind();
        }

原文地址:https://www.cnblogs.com/xiaoxiaomayi/p/2802009.html