Xml增删改查 和ling to Xml

<?xml version="1.0" encoding="utf-8"?>
<books>
  <book1>
    <name>水浒传</name>
    <author>作者</author>
  </book1>
  <Student studentId="10">
    <Name>我是学生1</Name>
    <Sex>
      <a></a>
    </Sex>
    <price name="价格" count="1000"    />
  </Student>
</books>

1增

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 using System.Xml;
 8 
 9 namespace ConsoleApplication10
10 {
11     class Program
12     {
13         static void Main(string[] args)
14         {
15             XmlDocument doc = new XmlDocument();
16             //先判断xml文件是否已经存在,如果存在,就追加;不存在,新建。
17             if(File.Exists("a.xml"))
18             {
19                 //存在
20                 //先加载进来
21                 doc.Load("a.xml");
22                 //获得根节点
23                  XmlElement gen=  doc.DocumentElement;
24 
25                 //给根节点添加子节点
26                  XmlElement student1 = doc.CreateElement("Student");
27                 //设置标签属性
28                  student1.SetAttribute("studentId","10");
29                  gen.AppendChild(student1);
30                 //添加子子标签
31                  XmlElement name1 = doc.CreateElement("Name");
32                  name1.InnerXml = "我是学生1";
33                  student1.AppendChild(name1);
34                 // XmlElement sex1 = doc.CreateElement("Sex"); sex1.InnerXml = "<a>男</a>";
35                  XmlElement sex1 = doc.CreateElement("Sex"); sex1.InnerXml = "";
36                  student1.AppendChild(sex1);
37             }
38             else
39             {
40             //不存在
41                 XmlDeclaration dec = doc.CreateXmlDeclaration("1.0","utf-8",null);
42                 doc.AppendChild(dec);
43                 XmlElement gen = doc.CreateElement("gen");
44                 doc.AppendChild(gen);
45 
46                 //给根节点添加子节点
47                 XmlElement student1 = doc.CreateElement("Student");
48                 //设置标签属性
49                 student1.SetAttribute("studentId", "10");
50                 gen.AppendChild(student1);
51                 //添加子子标签
52                 XmlElement name1 = doc.CreateElement("Name");
53                 name1.InnerXml = "我是学生1";
54                 student1.AppendChild(name1);
55                 // XmlElement sex1 = doc.CreateElement("Sex"); sex1.InnerXml = "<a>男</a>";
56                 XmlElement sex1 = doc.CreateElement("Sex"); sex1.InnerXml = "";
57                 student1.AppendChild(sex1);
58             }
59             //最终都要保存
60             doc.Save("a.xml");
61             Console.WriteLine("保存成功");
62         }
63     }
64 }
View Code

2删

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 using System.Xml;
 8 
 9 namespace ConsoleApplication10
10 {
11     class Program
12     {
13         static void Main(string[] args)
14         {
15         
16             XmlDocument doc = new XmlDocument();
17             doc.Load("a.xml");
18            // doc.RemoveAll();//不行,根节点不允许删除
19             XmlNode gen = doc.DocumentElement;
20             //gen.RemoveAll();//移除根节点下所有的子节点
21             #region 删除一个指定的标签
22             ////寻找指定的节点,注意path格式
23             //XmlNode xn = gen.SelectSingleNode("/books/Student/price[@name='价格']");
24             ////获得上面price节点的上节点
25             //XmlNode shangxn = doc.SelectSingleNode("/books/Student");
26             //shangxn.RemoveChild(xn);//删除方法必须是上一个节点删除下一个节点
27             #endregion
28 
29 
30             #region 删除一个指定的标签内的属性
31             //寻找指定标签
32             XmlNode xn = gen.SelectSingleNode("/books/Student/price[@name='价格']");
33             //删除指定标签内的属性
34             xn.Attributes.RemoveNamedItem("count");
35             #endregion
36 
37 
38             doc.Save("a.xml");
39             Console.WriteLine("删除成功");
40             Console.ReadLine();
41 
42 
43 
44         }
45     }
46 }
View Code

3查改

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 using System.Xml;
 8 
 9 namespace ConsoleApplication10
10 {
11     class Program
12     {
13         static void Main(string[] args)
14         {
15             #region 普通方法查询
16            // XmlDocument doc = new XmlDocument();
17            ////获得根节点
18            // XmlElement gen = doc.DocumentElement;
19            // //获得根节点下所有的子节点 
20            // XmlNodeList xnl = gen.ChildNodes;
21            // foreach (XmlNode xn in xnl)
22            // {
23            //     Console.WriteLine(xn.InnerText);//获取所有子节点的值
24            //     //但是如果有属性,就获取不到属性的值
25            // }
26 
27 
28            // //<Sex><a></a></Sex>,只有一个这样的标签
29            // XmlElement items = gen["Sex"];//根据标签查找
30            
31            // XmlNodeList xnl2 = items.ChildNodes;
32            // foreach (XmlNode xn in xnl2)
33            // {
34            //     Console.WriteLine(xn.Attributes["a"].Value);//得到“男”
35            // }
36            // //最终都要保存
37            // doc.Save("a.xml");
38            // Console.WriteLine("保存成功");
39             #endregion
40 
41             #region 使用XPath的方式来读取XML文件
42             XmlDocument doc = new XmlDocument();
43             doc.Load("a.xml");
44             //获得根节点
45             XmlElement gen = doc.DocumentElement;
46 
47             //XmlNode xn = gen.SelectSingleNode("/books/book1/name");//  "/根节点/子节点/包裹值得标签"
48             //Console.WriteLine(xn.InnerText);
49 
50             XmlNode xn = gen.SelectSingleNode("/books/Student/price[@name='价格']");//  "/根节点/子节点/子节点内的标签[@标签属性='属性值']"
51             Console.WriteLine(xn.Attributes["count"].Value);//取值 count为标签内属性
52             xn.Attributes["count"].Value = "2000";//修改值
53 
54 
55             doc.Save("a.xml");//保存
56             Console.ReadKey();
57 
58             #endregion
59 
60 
61 
62         }
63     }
64 }
View Code

linq to Xml

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;

namespace xml
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        static string ddd = "ddd.xml";//全局变量,将要操作对的文件
        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Text = LoadForm().ToString();

        }
        /// <summary>
        /// 加载原始数据
        /// </summary>
        /// <returns></returns>
        public static XDocument LoadForm()
        {
            
            XDocument newXelem = null;
            if (File.Exists(ddd))
                newXelem = XDocument.Load(ddd);
            else
            {
                List<people> pList = new List<people>();
                for (int i = 0; i < 10; i++)
                    pList.Add(new people { name="name"+i, age=100+i});
                newXelem = new XDocument("people",
                   from p in pList select new XElement("person",
                                              new XAttribute("age",p.age),
                                              new XElement("name",p.name))
                    );
            }
            newXelem.Save(ddd);
            return newXelem;
        }


        /// <summary>
        /// parse和load方法加载xml文件
        /// </summary>
        public static void ParseAndLoadExistXml()
        {
            string xml = File.ReadAllText("ccc.xml");
            //parse方法
            XElement newElem = XElement.Parse(xml);
            Console.WriteLine(newElem);

            Console.WriteLine("-----------");
            //load方法
            XElement newElem2 = XElement.Load("aaa.xml");
            Console.WriteLine(newElem2);
        }

        /// <summary>
        /// 从数据源(数组或集合)中获取数据创建xml文件
        /// </summary>
        public static void MakeXelementFormArray()
        {
            List<people> pList = new List<people>();
            for (int i = 0; i < 10; i++)
            {
                pList.Add(new people { name = "name" + i, age = 100 + i });
            }
            XElement peopleDoc = new XElement("pepole",
                //linq加载数据源数据
                from p in pList
                select new XElement("person",
                            new XAttribute("age", p.age),
                            new XElement("name", p.name))
                );
            peopleDoc.Save("ccc.xml");
        }
        /// <summary>
        /// 创建简单xml文件2
        /// </summary>
        public static void CreateFullXdocment()
        {
            XDocument invenDoc = new XDocument(
                new XDeclaration("1.0", "utf-8", "yes"),
                new XComment("current inventory of Cars"),
                new XProcessingInstruction("xml-stylesheet", "href='MyStyle'"),
                new XElement("inventory",
                     new XElement("Car", new XAttribute("ID", "1"),
                       new XElement("color", "Green"),
                       new XElement("make", "BMW"),
                       new XElement("petname", "stan")),
                     new XElement("Car", new XAttribute("ID", "2"),
                       new XElement("color", "Pink"),
                       new XElement("make", "YuGo"),
                       new XElement("petname", "Melvin"))
                     )
                );

            invenDoc.Save("bbb.xml");
        }

        /// <summary>
        /// 创建简单xml文件1
        /// </summary>
        public static void BuildDocWithLinqToXml()
        {
            XElement doc =
               new XElement("Inventory",
                   new XElement("Car", new XAttribute("ID", "1000"),
                      new XElement("PetName", "Jimbo"),
                      new XElement("Color", "Red"),
                      new XElement("Make", "Ford")
                   ));
            doc.Descendants("PetName").Remove();
            doc.Save("aaa.xml");
        }

        private void btAdd_Click(object sender, EventArgs e)
        {
            try
            {
                string name = tbName.Text.Trim();
                int age = int.Parse(tbAge.Text.Trim());
                InsertPeople(name,age);

            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());
            }
        }
        public static void InsertPeople(string name,int age)
        {
            XDocument doc = XDocument.Load(ddd);
            Random r = new Random();
            XElement xele = new XElement("person",
                new XAttribute("ID",r.Next(5000)),
                new XAttribute("age",age),
                new XElement("name",name+age));
            doc.Descendants("people").Last().Add(xele);
            doc.Save(ddd);
        }

        private void btAurey_Click(object sender, EventArgs e)
        {
            SearchByAge(int.Parse(tbQuery.Text.Trim()));
        }
        /// <summary>
        /// 根据属性(年龄)来查找符合条件的人的姓名
        /// </summary>
        /// <param name="age"></param>
        public static void SearchByAge(int age)
        {
            XDocument doc = XDocument.Load(ddd);
            //查找
            var ageInfo = from person in doc.Descendants("person")
                          where (int)person.Attribute("age") < age
                          select person.Element("name").Value;
            string data = string.Empty;
            foreach (var item in ageInfo.Distinct())
            {
                data += item + "===";
            }
            MessageBox.Show(data);

        }
    }
    class people
    {
        public string name { get; set; }
        public int age { get; set; }
    }
}
View Code

完!!

原文地址:https://www.cnblogs.com/wwz-wwz/p/6396796.html