首页 > 代码库 > XML文件的一些操作

XML文件的一些操作

XML 是被设计用来传输和存储数据的,

XML 必须含有且仅有一个 根节点元素(没有根节点会报错)

源码下载 http://pan.baidu.com/s/1ge2lpM7

好了,我们 先看一个 XML 文件(Cartoon.xml)

<?xml version="1.0" encoding="utf-8"?>
<Cartoon>
  <Character Company="DC">
    <Name>超人</Name>
    <Age>28</Age>
  </Character>
  <Character Company="Marve">
    <Name>雷神</Name>
    <Age>30</Age>
  </Character>
</Cartoon>

 

第二个 XML 文件 (Attribute.xml)

<?xml version="1.0" encoding="utf-8"?>
<Cartoon>
  <Character Name="超人" Company="DC" Age="28" />
  <Character Name="雷神" Company="Marve" Age="30" />
</Cartoon>

 

既然是小型存储文件,就避免不了.

 

 技术分享

 

 

全部 方法代码 如下 (用了两种方法 ).

 

using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;

namespace XML_Demo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //创建XML
        private void btn_Create_XML_Click(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            XmlDeclaration describe = doc.CreateXmlDeclaration("1.0", "utf-8", null); // 创建 描述信息
            doc.AppendChild(describe); // 写入描述

            XmlElement cartoon = doc.CreateElement("Cartoon"); //创建根节点
            doc.AppendChild(cartoon); // 写入根节点

            //子节点1
            XmlElement character1 = doc.CreateElement("Character");
            character1.SetAttribute("Company", "DC");

            XmlElement name1 = doc.CreateElement("Name");
            name1.InnerText = "超人";
            character1.AppendChild(name1);

            XmlElement age1 = doc.CreateElement("Age");
            age1.InnerText = "28";
            character1.AppendChild(age1);
            cartoon.AppendChild(character1); //子节点写入根节点

            //子节点2
            XmlElement character2 = doc.CreateElement("Character");
            character2.SetAttribute("Company", "Marve");

            XmlElement name2 = doc.CreateElement("Name");
            name2.InnerText = "雷神";
            character2.AppendChild(name2);

            XmlElement age2 = doc.CreateElement("Age");
            age2.InnerText = "30";
            character2.AppendChild(age2);
            cartoon.AppendChild(character2); //子节点写入根节点

            doc.Save(@"C:\Cartoon.xml");
            Console.WriteLine("写入成功!");
        }

        //查询XML
        private void btn_Search_Click(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(@"C:\Cartoon.xml");

            //获取根节点
            XmlElement superHeroes = doc.DocumentElement;

            // 获取子节点的集合
            XmlNodeList heroes = superHeroes.ChildNodes;

            foreach (XmlNode hero in heroes)
            {
                Console.WriteLine(hero.SelectSingleNode("Name").InnerText + ":" +
                                  hero.SelectSingleNode("Age").InnerText);
            }
        }

        //修改XML
        private void btn_Edit_Click(object sender, EventArgs e)
        {

            XmlDocument doc = new XmlDocument();
            var file = @"C:\Cartoon.xml";
            if (File.Exists(file))
            {
                doc.Load(file);
                //获取根节点
                XmlNode root = doc.DocumentElement;
                //获取节点的所有子节点
                XmlNodeList characters = root.ChildNodes;
                foreach (XmlNode hero in characters)
                {
                    string node = hero.SelectSingleNode("Name").InnerText;
                    if (node == "超人")
                    {
                        XmlNode age = hero.SelectSingleNode("Age");
                        age.InnerText = "99";
                        doc.Save(file);
                        Console.WriteLine("修改成功!");
                    }
                }
            }
            else
            {
                Console.WriteLine("文件不存在!");
            }
        }

        //修改XML(追加)
        private void btn_Edit_Add_Click(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            var file = @"C:\Cartoon.xml";
            if (File.Exists(file))
            {
                doc.Load(file);
                //获取根节点
                XmlElement cartoonNew = doc.DocumentElement;
                XmlElement characterNew = doc.CreateElement("Character");
                characterNew.SetAttribute("Company", "DC");

                XmlElement nameNew = doc.CreateElement("Name");
                nameNew.InnerText = "Doctor Manhattan";
                characterNew.AppendChild(nameNew);

                XmlElement ageNew = doc.CreateElement("Age");
                ageNew.InnerText = "24";
                characterNew.AppendChild(ageNew);
                cartoonNew.AppendChild(characterNew); //子节点写入根节点
                doc.Save(file);
                Console.WriteLine("添加成功!");

            }
            else
            {
                Console.WriteLine("文件不存在!");
            }
        }

        //删除XML
        private void btn_Del_Click(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            var file = @"C:\Cartoon.xml";
            doc.Load(file);
            XmlNode root = doc.SelectSingleNode("Cartoon");
            //root.RemoveAll(); //删除根节点下的 所有节点
            foreach (XmlNode xn in root.ChildNodes)
            {
                if (xn.FirstChild.InnerText == "超人")
                {
                    root.RemoveChild(xn);
                }
            }

            doc.Save(file);
            Console.WriteLine("删除成功");
        }


        //创建XML2
        private void btn_Create_XML2_Click(object sender, EventArgs e)
        {
            XElement xel = new XElement("Cartoon",
                new XElement("Character",
                    new XAttribute("Company", "DC"),
                    new XElement("Name", "超人"),
                    new XElement("Age", "28")),
                new XElement("Character",
                    new XAttribute("Company", "Marve"),
                    new XElement("Name", "雷神"),
                    new XElement("Age", "30"))
            );
            XDocument xdoc = new XDocument(xel);
            xdoc.Save(@"c:\Cartoon2.xml");
        }

        //查询XML2
        private void btn_Search2_Click(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(@"C:\Cartoon2.xml");
            XmlNodeList characterList = doc.SelectNodes("/Character");
            foreach (XmlNode item in characterList)
            {
                Console.WriteLine(item.SelectSingleNode("Name").InnerText+":"+
                                  item.SelectSingleNode("Age").InnerText);
            }
        }

        //修改XML2
        private void btn_Edit2_Click(object sender, EventArgs e)
        {
            XElement doc = XElement.Load(@"C:\Cartoon2.xml");
            XElement heroes = (from p in doc.Elements() where p.Element("Name").Value =http://www.mamicode.com/= "超人" select p).FirstOrDefault();
            if (heroes != null)
            {
                heroes.Element("Age").Value = http://www.mamicode.com/"99";
                doc.Save(@"C:\Cartoon2.xml");
                Console.WriteLine("添加成功!");
            }

        }

        //删除XML2
        private void btn_Del2_Click(object sender, EventArgs e)
        {
            XElement doc = XElement.Load(@"C:\Cartoon2.xml");
            XElement xchild = doc.Descendants("Name").Single(p => p.Value.Equals("超人"));
            XElement nameNode = xchild.Parent;
            nameNode.Remove();
            doc.Save(@"C:\Cartoon2.xml");
        }

        //创建多属性XML
        private void btn_XML_Attribute_Click(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            XmlDeclaration describe = doc.CreateXmlDeclaration("1.0", "utf-8", null); 
            doc.AppendChild(describe);

            XmlElement cartoon = doc.CreateElement("Cartoon");
            doc.AppendChild(cartoon);

            XmlElement character1 = doc.CreateElement("Character");
            character1.SetAttribute("Name", "超人");
            character1.SetAttribute("Company","DC");
            character1.SetAttribute("Age", "28");
            cartoon.AppendChild(character1);

            XmlElement character2 = doc.CreateElement("Character");
            character2.SetAttribute("Name", "雷神");
            character2.SetAttribute("Company", "Marve");
            character2.SetAttribute("Age", "30");
            cartoon.AppendChild(character2);

            doc.Save(@"C:\Attribute.xml");
            Console.WriteLine("写入成功!");
        }

        //查询多属性XML
        private void btn_Search_Attribute_Click(object sender, EventArgs e)
        {
            var file = @"C:\Attribute.xml";
            XmlDocument doc = new XmlDocument();
            doc.Load(file);
            XmlNodeList xnl = doc.SelectNodes("/Cartoon/Character");
            foreach (XmlNode item in xnl)
            {
                Console.WriteLine(item.Attributes["Name"].Value );
            }
        }

        //修改多属性XML
        private void btn_Edit_Attribute_Click(object sender, EventArgs e)
        {
            var file = @"C:\Attribute.xml";
            XElement doc = XElement.Load(file);
            XElement heroes = (from p in doc.Elements() where p.Attribute("Name").Value =http://www.mamicode.com/= "超人" select p).FirstOrDefault();
            if (heroes != null)
            {
                heroes.Attribute("Age").Value = http://www.mamicode.com/"99";
                doc.Save(file);
                Console.WriteLine("修改成功!");
            }

        }

        //删除多属性XML
        private void btn_Del_Attribute_Click(object sender, EventArgs e)
        {
            var file = @"C:\Attribute.xml";
            XElement xl = XDocument.Load(file).Root;
            xl.Elements("Character").Where(el => el.Attribute("Name").Value.Equals("超人")).Remove();
            xl.Save(file);
            Console.WriteLine("修改成功!");
        }

        //删除多属性XML2
        private void btn_Del_Attribute2_Click(object sender, EventArgs e)
        {
            var file = @"C:\Attribute.xml";
            XmlDocument doc = new XmlDocument();
            doc.Load(file);
            XmlElement root = doc.DocumentElement;
            XmlNodeList element = doc.SelectNodes("/Cartoon/Character");
            foreach (XmlNode item in element)
            {
                Console.WriteLine(item.Attributes["Name"].Value);
                if (item.Attributes["Name"].Value =http://www.mamicode.com/= "超人")
                {
                    root.RemoveChild(item);
                }
            }
            doc.Save(file);
        }
    }
}

 

窗体设计代码 (如果不想拖控件,可以复制过去)

 

技术分享
  1 namespace XML_Demo
  2 {
  3     partial class Form1
  4     {
  5         /// <summary>
  6         /// 必需的设计器变量。
  7         /// </summary>
  8         private System.ComponentModel.IContainer components = null;
  9 
 10         /// <summary>
 11         /// 清理所有正在使用的资源。
 12         /// </summary>
 13         /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
 14         protected override void Dispose(bool disposing)
 15         {
 16             if (disposing && (components != null))
 17             {
 18                 components.Dispose();
 19             }
 20             base.Dispose(disposing);
 21         }
 22 
 23         #region Windows 窗体设计器生成的代码
 24 
 25         /// <summary>
 26         /// 设计器支持所需的方法 - 不要修改
 27         /// 使用代码编辑器修改此方法的内容。
 28         /// </summary>
 29         private void InitializeComponent()
 30         {
 31             this.btn_Create_XML = new System.Windows.Forms.Button();
 32             this.btn_Create_XML2 = new System.Windows.Forms.Button();
 33             this.btn_Search = new System.Windows.Forms.Button();
 34             this.btn_Edit_Add = new System.Windows.Forms.Button();
 35             this.btn_Edit = new System.Windows.Forms.Button();
 36             this.btn_Del = new System.Windows.Forms.Button();
 37             this.btn_Search2 = new System.Windows.Forms.Button();
 38             this.btn_Edit2 = new System.Windows.Forms.Button();
 39             this.btn_Del2 = new System.Windows.Forms.Button();
 40             this.btn_XML_Attribute = new System.Windows.Forms.Button();
 41             this.btn_Search_Attribute = new System.Windows.Forms.Button();
 42             this.btn_Edit_Attribute = new System.Windows.Forms.Button();
 43             this.btn_Del_Attribute = new System.Windows.Forms.Button();
 44             this.btn_Del_Attribute2 = new System.Windows.Forms.Button();
 45             this.SuspendLayout();
 46             // 
 47             // btn_Create_XML
 48             // 
 49             this.btn_Create_XML.Location = new System.Drawing.Point(13, 12);
 50             this.btn_Create_XML.Name = "btn_Create_XML";
 51             this.btn_Create_XML.Size = new System.Drawing.Size(95, 23);
 52             this.btn_Create_XML.TabIndex = 0;
 53             this.btn_Create_XML.Text = "创建XML";
 54             this.btn_Create_XML.UseVisualStyleBackColor = true;
 55             this.btn_Create_XML.Click += new System.EventHandler(this.btn_Create_XML_Click);
 56             // 
 57             // btn_Create_XML2
 58             // 
 59             this.btn_Create_XML2.Location = new System.Drawing.Point(137, 12);
 60             this.btn_Create_XML2.Name = "btn_Create_XML2";
 61             this.btn_Create_XML2.Size = new System.Drawing.Size(75, 23);
 62             this.btn_Create_XML2.TabIndex = 3;
 63             this.btn_Create_XML2.Text = "创建XML2";
 64             this.btn_Create_XML2.UseVisualStyleBackColor = true;
 65             this.btn_Create_XML2.Click += new System.EventHandler(this.btn_Create_XML2_Click);
 66             // 
 67             // btn_Search
 68             // 
 69             this.btn_Search.Location = new System.Drawing.Point(13, 57);
 70             this.btn_Search.Name = "btn_Search";
 71             this.btn_Search.Size = new System.Drawing.Size(95, 23);
 72             this.btn_Search.TabIndex = 4;
 73             this.btn_Search.Text = "查询XML";
 74             this.btn_Search.UseVisualStyleBackColor = true;
 75             this.btn_Search.Click += new System.EventHandler(this.btn_Search_Click);
 76             // 
 77             // btn_Edit_Add
 78             // 
 79             this.btn_Edit_Add.Location = new System.Drawing.Point(13, 139);
 80             this.btn_Edit_Add.Name = "btn_Edit_Add";
 81             this.btn_Edit_Add.Size = new System.Drawing.Size(95, 23);
 82             this.btn_Edit_Add.TabIndex = 5;
 83             this.btn_Edit_Add.Text = "修改XML(追加)";
 84             this.btn_Edit_Add.UseVisualStyleBackColor = true;
 85             this.btn_Edit_Add.Click += new System.EventHandler(this.btn_Edit_Add_Click);
 86             // 
 87             // btn_Edit
 88             // 
 89             this.btn_Edit.Location = new System.Drawing.Point(13, 100);
 90             this.btn_Edit.Name = "btn_Edit";
 91             this.btn_Edit.Size = new System.Drawing.Size(95, 23);
 92             this.btn_Edit.TabIndex = 6;
 93             this.btn_Edit.Text = "修改XML";
 94             this.btn_Edit.UseVisualStyleBackColor = true;
 95             this.btn_Edit.Click += new System.EventHandler(this.btn_Edit_Click);
 96             // 
 97             // btn_Del
 98             // 
 99             this.btn_Del.Location = new System.Drawing.Point(13, 179);
100             this.btn_Del.Name = "btn_Del";
101             this.btn_Del.Size = new System.Drawing.Size(95, 23);
102             this.btn_Del.TabIndex = 7;
103             this.btn_Del.Text = "删除XML";
104             this.btn_Del.UseVisualStyleBackColor = true;
105             this.btn_Del.Click += new System.EventHandler(this.btn_Del_Click);
106             // 
107             // btn_Search2
108             // 
109             this.btn_Search2.Location = new System.Drawing.Point(137, 57);
110             this.btn_Search2.Name = "btn_Search2";
111             this.btn_Search2.Size = new System.Drawing.Size(75, 23);
112             this.btn_Search2.TabIndex = 8;
113             this.btn_Search2.Text = "查询XML2";
114             this.btn_Search2.UseVisualStyleBackColor = true;
115             this.btn_Search2.Click += new System.EventHandler(this.btn_Search2_Click);
116             // 
117             // btn_Edit2
118             // 
119             this.btn_Edit2.Location = new System.Drawing.Point(137, 100);
120             this.btn_Edit2.Name = "btn_Edit2";
121             this.btn_Edit2.Size = new System.Drawing.Size(75, 23);
122             this.btn_Edit2.TabIndex = 9;
123             this.btn_Edit2.Text = "修改XML2";
124             this.btn_Edit2.UseVisualStyleBackColor = true;
125             this.btn_Edit2.Click += new System.EventHandler(this.btn_Edit2_Click);
126             // 
127             // btn_Del2
128             // 
129             this.btn_Del2.Location = new System.Drawing.Point(137, 179);
130             this.btn_Del2.Name = "btn_Del2";
131             this.btn_Del2.Size = new System.Drawing.Size(75, 23);
132             this.btn_Del2.TabIndex = 10;
133             this.btn_Del2.Text = "删除XML2";
134             this.btn_Del2.UseVisualStyleBackColor = true;
135             this.btn_Del2.Click += new System.EventHandler(this.btn_Del2_Click);
136             // 
137             // btn_XML_Attribute
138             // 
139             this.btn_XML_Attribute.Location = new System.Drawing.Point(252, 12);
140             this.btn_XML_Attribute.Name = "btn_XML_Attribute";
141             this.btn_XML_Attribute.Size = new System.Drawing.Size(118, 23);
142             this.btn_XML_Attribute.TabIndex = 11;
143             this.btn_XML_Attribute.Text = "创建多属性XML";
144             this.btn_XML_Attribute.UseVisualStyleBackColor = true;
145             this.btn_XML_Attribute.Click += new System.EventHandler(this.btn_XML_Attribute_Click);
146             // 
147             // btn_Search_Attribute
148             // 
149             this.btn_Search_Attribute.Location = new System.Drawing.Point(252, 57);
150             this.btn_Search_Attribute.Name = "btn_Search_Attribute";
151             this.btn_Search_Attribute.Size = new System.Drawing.Size(118, 23);
152             this.btn_Search_Attribute.TabIndex = 12;
153             this.btn_Search_Attribute.Text = "查询多属性XML";
154             this.btn_Search_Attribute.UseVisualStyleBackColor = true;
155             this.btn_Search_Attribute.Click += new System.EventHandler(this.btn_Search_Attribute_Click);
156             // 
157             // btn_Edit_Attribute
158             // 
159             this.btn_Edit_Attribute.Location = new System.Drawing.Point(252, 100);
160             this.btn_Edit_Attribute.Name = "btn_Edit_Attribute";
161             this.btn_Edit_Attribute.Size = new System.Drawing.Size(118, 23);
162             this.btn_Edit_Attribute.TabIndex = 13;
163             this.btn_Edit_Attribute.Text = "修改多属性XML";
164             this.btn_Edit_Attribute.UseVisualStyleBackColor = true;
165             this.btn_Edit_Attribute.Click += new System.EventHandler(this.btn_Edit_Attribute_Click);
166             // 
167             // btn_Del_Attribute
168             // 
169             this.btn_Del_Attribute.Location = new System.Drawing.Point(252, 139);
170             this.btn_Del_Attribute.Name = "btn_Del_Attribute";
171             this.btn_Del_Attribute.Size = new System.Drawing.Size(118, 23);
172             this.btn_Del_Attribute.TabIndex = 14;
173             this.btn_Del_Attribute.Text = "删除多属性XML";
174             this.btn_Del_Attribute.UseVisualStyleBackColor = true;
175             this.btn_Del_Attribute.Click += new System.EventHandler(this.btn_Del_Attribute_Click);
176             // 
177             // btn_Del_Attribute2
178             // 
179             this.btn_Del_Attribute2.Location = new System.Drawing.Point(252, 178);
180             this.btn_Del_Attribute2.Name = "btn_Del_Attribute2";
181             this.btn_Del_Attribute2.Size = new System.Drawing.Size(118, 23);
182             this.btn_Del_Attribute2.TabIndex = 15;
183             this.btn_Del_Attribute2.Text = "删除多属性XML2";
184             this.btn_Del_Attribute2.UseVisualStyleBackColor = true;
185             this.btn_Del_Attribute2.Click += new System.EventHandler(this.btn_Del_Attribute2_Click);
186             // 
187             // Form1
188             // 
189             this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
190             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
191             this.ClientSize = new System.Drawing.Size(410, 249);
192             this.Controls.Add(this.btn_Del_Attribute2);
193             this.Controls.Add(this.btn_Del_Attribute);
194             this.Controls.Add(this.btn_Edit_Attribute);
195             this.Controls.Add(this.btn_Search_Attribute);
196             this.Controls.Add(this.btn_XML_Attribute);
197             this.Controls.Add(this.btn_Del2);
198             this.Controls.Add(this.btn_Edit2);
199             this.Controls.Add(this.btn_Search2);
200             this.Controls.Add(this.btn_Del);
201             this.Controls.Add(this.btn_Edit);
202             this.Controls.Add(this.btn_Edit_Add);
203             this.Controls.Add(this.btn_Search);
204             this.Controls.Add(this.btn_Create_XML2);
205             this.Controls.Add(this.btn_Create_XML);
206             this.Name = "Form1";
207             this.Text = "XML文件的 增删改查";
208             this.ResumeLayout(false);
209 
210         }
211 
212         #endregion
213 
214         private System.Windows.Forms.Button btn_Create_XML;
215         private System.Windows.Forms.Button btn_Create_XML2;
216         private System.Windows.Forms.Button btn_Search;
217         private System.Windows.Forms.Button btn_Edit_Add;
218         private System.Windows.Forms.Button btn_Edit;
219         private System.Windows.Forms.Button btn_Del;
220         private System.Windows.Forms.Button btn_Search2;
221         private System.Windows.Forms.Button btn_Edit2;
222         private System.Windows.Forms.Button btn_Del2;
223         private System.Windows.Forms.Button btn_XML_Attribute;
224         private System.Windows.Forms.Button btn_Search_Attribute;
225         private System.Windows.Forms.Button btn_Edit_Attribute;
226         private System.Windows.Forms.Button btn_Del_Attribute;
227         private System.Windows.Forms.Button btn_Del_Attribute2;
228     }
229 }
Form1.Designer.cs

 

 

 

XML文件的一些操作