XML

基础

  • 可扩展的标记语言
  • 优点:
    • 容易读懂
    • 格式标准任何语言都内置了XML分析引擎,不用单独进行文件分析引擎的编写
  • Node :所看到的均是节点
  • Element:元素就是标签
  • 节点包含元素
  • 大小写敏感

写入XML

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace _01WriteXML
{
    class Program
    {
        static void Main(string[] args)
        {
            //1.创建一个XML文档对象
            XmlDocument doc = new XmlDocument();
            //2.创建第一行描述信息
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            //3.将创建的第一行数据添加到文档中
            doc.AppendChild(dec);

            //4.给文档添加根节点
            XmlElement books = doc.CreateElement("Books");
            //5.将根节点添加给文档对象
            doc.AppendChild(books);

            //6.给根节点添加子节点
            XmlElement book1 = doc.CreateElement("Book");
            //7.将子结点book1添加到根节点下
            books.AppendChild(book1);

            //8.给book1添加子节点
            XmlElement book1Name = doc.CreateElement("BookName");
            //9.设置标签中显示的文本
            book1Name.InnerText = "水浒传";
            book1.AppendChild(book1Name);

            XmlElement book1Author = doc.CreateElement("Author");
            book1Author.InnerText = "<author>匿名</author>";
            book1.AppendChild(book1Author);

            XmlElement book1Price = doc.CreateElement("Price");
            book1Price.InnerXml = "<author>匿名</author>";
            book1.AppendChild(book1Price);

            XmlElement book1Des = doc.CreateElement("Des");
            book1Des.InnerXml = "好看呢";
            book1.AppendChild(book1Des);

            doc.Save("Book.xml");
            Console.WriteLine("保存成功!");
            Console.ReadKey();
        }
    }
}
//XML
<?xml version="1.0" encoding="utf-8"?>
<Books>
  <Book>
    <BookName>水浒传</BookName>
    <Author>&lt;author&gt;匿名&lt;/author&gt;</Author>
    <Price>
      <author>匿名</author>
    </Price>
    <Des>好看呢</Des>
  </Book>
</Books>

//InnerXml和InnerText的区别
book1Price.InnerXml = "<author>匿名</author>";
在XML中显示:
    <Price>
      <author>匿名</author>
    </Price>
    
book1Author.InnerText = "<author>匿名</author>";
在XML中显示:
<Author>&lt;author&gt;匿名&lt;/author&gt;</Author>

写入带属性的XML

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace _02WriteXMLWithAttribute
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            doc.AppendChild(dec);

            XmlElement order = doc.CreateElement("Order");
            doc.AppendChild(order);

            XmlElement customerName = doc.CreateElement("CustomerName");
            customerName.InnerXml = "刘XX";
            order.AppendChild(customerName);

            XmlElement orderNumber = doc.CreateElement("OrderNumber");
            orderNumber.InnerXml = "100";
            order.AppendChild(orderNumber);

            XmlElement items = doc.CreateElement("Items");
            order.AppendChild(items);

            XmlElement orderItem1 = doc.CreateElement("OrderItem1");
            orderItem1.SetAttribute("Name", "锅巴");
            orderItem1.SetAttribute("Count", "10");
            orderItem1.SetAttribute("Price", "12");
            items.AppendChild(orderItem1);

            XmlElement orderItem2 = doc.CreateElement("OrderItem2");
            orderItem2.SetAttribute("Name", "杯子");
            orderItem2.SetAttribute("Count", "6");
            orderItem2.SetAttribute("Price", "8");
            items.AppendChild(orderItem2);

            doc.Save("Order.xml");
            Console.WriteLine("保存成功!");
            Console.ReadKey();
        }
    }
}
//XML:
<?xml version="1.0" encoding="utf-8"?>
<Order>
  <CustomerName>刘XX</CustomerName>
  <OrderNumber>100</OrderNumber>
  <Items>
    <OrderItem1 Name="锅巴" Count="10" Price="12" />
    <OrderItem2 Name="杯子" Count="6" Price="8" />
  </Items>
</Order>

文档对象模型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace _03DocumentObjectModel
{
    class Student
    {
        public int Age { get; set; }
        public string Name { get; set; }
        public int ID { get; set; }
        public char Gender { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<Student> list = new List<Student>();
            list.Add(new Student() { ID = 1, Name = "张三", Gender = '男', Age = 12 });
            list.Add(new Student() { ID = 2, Name = "李四", Gender = '男', Age = 30 });
            list.Add(new Student() { ID = 3, Name = "王五", Gender = '男', Age = 5 });
            list.Add(new Student() { ID = 4, Name = "张丽", Gender = '女', Age = 18 });

            XmlDocument doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            doc.AppendChild(dec);

            XmlElement person = doc.CreateElement("Person");
            doc.AppendChild(person);

            //通过循环List集合,获得所有对象以节点的形式添加到XML文档中
            for(int i = 0;i<list.Count;i++)
            {
                XmlElement student = doc.CreateElement("Student");
                student.SetAttribute("studentID", list[i].ID.ToString());

                XmlElement name = doc.CreateElement("Name");
                name.InnerXml = list[i].Name;

                XmlElement gender = doc.CreateElement("Gender");
                gender.InnerXml = list[i].Gender.ToString();

                XmlElement age = doc.CreateElement("Age");
                age.InnerXml = list[i].Age.ToString();

                person.AppendChild(student);
                student.AppendChild(name);
                student.AppendChild(gender);
                student.AppendChild(age);
            }

            doc.Save("Student.xml");
            Console.WriteLine("保存成功!");
            Console.ReadKey();
        }
    }
}
//XML:
<?xml version="1.0" encoding="utf-8"?>
<Person>
  <Student studentID="1">
    <Name>张三</Name>
    <Gender>男</Gender>
    <Age>12</Age>
  </Student>
  <Student studentID="2">
    <Name>李四</Name>
    <Gender>男</Gender>
    <Age>30</Age>
  </Student>
  <Student studentID="3">
    <Name>王五</Name>
    <Gender>男</Gender>
    <Age>5</Age>
  </Student>
  <Student studentID="4">
    <Name>张丽</Name>
    <Gender>女</Gender>
    <Age>18</Age>
  </Student>
</Person>

对XML增加

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.IO;
namespace _04AddXML
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            //1.首先判断xml文档是否存在,若存在,则追加,否则创建一个
            if(File.Exists("Student.xml"))
            {
                //2.加载进来
                doc.Load("Student.xml");
                //3.获得根节点
                XmlElement person = doc.DocumentElement;
                //4.追加
                XmlElement student = doc.CreateElement("Student");
                student.SetAttribute("studentID", "10");
                person.AppendChild(student);
                XmlElement name = doc.CreateElement("Name");
                name.InnerXml = "赵十";
                student.AppendChild(name);
                XmlElement gender = doc.CreateElement("Gender");
                gender.InnerXml = "女";
                student.AppendChild(gender);
                XmlElement age = doc.CreateElement("Age");
                age.InnerXml = "18";
                student.AppendChild(age);
            }
            else
            {
                //2.不存在,则创建描述文件、根节点
                XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
                doc.AppendChild(dec);
                XmlElement person = doc.CreateElement("Person");
                doc.AppendChild(person);
                //3.追加
                XmlElement student = doc.CreateElement("Student");
                student.SetAttribute("studentID", "11");
                person.AppendChild(student);
                XmlElement name = doc.CreateElement("Name");
                name.InnerXml = "赵十一";
                student.AppendChild(name);
                XmlElement gender = doc.CreateElement("Gender");
                gender.InnerXml = "男";
                student.AppendChild(gender);
                XmlElement age = doc.CreateElement("Age");
                age.InnerXml = "16";
                student.AppendChild(age);

            }
            doc.Save("Student.xml");
            Console.WriteLine("保存成功!");
            Console.ReadKey();
        }
    }
}
//XML:
//已存在XML
<?xml version="1.0" encoding="utf-8"?>
<Person>
  <Student studentID="1">
    <Name>张三</Name>
    <Gender>男</Gender>
    <Age>12</Age>
  </Student>
  <Student studentID="2">
    <Name>李四</Name>
    <Gender>男</Gender>
    <Age>30</Age>
  </Student>
  <Student studentID="3">
    <Name>王五</Name>
    <Gender>男</Gender>
    <Age>5</Age>
  </Student>
  <Student studentID="4">
    <Name>张丽</Name>
    <Gender>女</Gender>
    <Age>18</Age>
  </Student>
  <Student studentID="10">
    <Name>赵十</Name>
    <Gender>女</Gender>
    <Age>18</Age>
  </Student>
</Person>
//不存在XML
<?xml version="1.0" encoding="utf-8"?>
<Person>
  <Student studentID="11">
    <Name>赵十一</Name>
    <Gender>男</Gender>
    <Age>16</Age>
  </Student>
</Person>

读取XML

  • xml文件名不区分大小写,均可读取
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace _05ReadXML
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            //加载xml
            doc.Load("Order.xml");
            //获得根节点
            XmlElement order = doc.DocumentElement;
            //获得根节点下面的所有节点
            XmlNodeList xnl = order.ChildNodes;
            foreach(XmlNode item in xnl)
            {
                Console.WriteLine(item.InnerText);
            }

            XmlElement items = order["Items"];
            XmlNodeList xnl2 = items.ChildNodes;
            foreach(XmlNode item in xnl2)
            {
                Console.WriteLine(item.Attributes["Name"].Value);
                Console.WriteLine(item.Attributes["Count"].Value);
            }
            Console.ReadKey();
        }
    }
}
//XML:
<?xml version="1.0" encoding="utf-8"?>
<Order>
  <CustomerName>刘XX</CustomerName>
  <OrderNumber>100</OrderNumber>
  <Items>
    <OrderItem1 Name="锅巴" Count="10" Price="12" />
    <OrderItem2 Name="杯子" Count="6" Price="8" />
  </Items>
</Order>
//输出:
刘XX
100

锅巴
10
杯子
6

修改XML

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace _06AlterXML
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            //加载xml
            doc.Load("Order.xml");
            //获得根节点
            XmlElement order = doc.DocumentElement;
            //获得根节点下面的所有节点
            XmlNodeList xnl = order.ChildNodes;
            foreach (XmlNode item in xnl)
            {
                Console.WriteLine(item.InnerText);
            }

            XmlElement items = order["Items"];
            XmlNodeList xnl2 = items.ChildNodes;
            foreach (XmlNode item in xnl2)
            {
                Console.WriteLine(item.Attributes["Name"].Value);
                Console.WriteLine(item.Attributes["Count"].Value);
                //修改
                if(item.Attributes["Name"].Value == "锅巴")
                {
                    item.Attributes["Count"].Value = "+10";
                }
            }
            doc.Save("Order.xml");
            Console.ReadKey();
        }
    }
}
//XML:
<?xml version="1.0" encoding="utf-8"?>
<Order>
  <CustomerName>刘XX</CustomerName>
  <OrderNumber>100</OrderNumber>
  <Items>
    <OrderItem1 Name="锅巴" Count="+10" Price="12" />
    <OrderItem2 Name="杯子" Count="6" Price="8" />
  </Items>
</Order>

使用XPath的方式读XML

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace _07ReadXMLWithXPath
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("Order.xml");
            //获得根节点
            XmlElement order = doc.DocumentElement;
            XmlNode xn = order.SelectSingleNode("/Order/Items/OrderItem1[@Name='锅巴']");
            Console.WriteLine(xn.Attributes["Name"].Value);
            Console.ReadKey();
        }
    }
}
//XML:
<?xml version="1.0" encoding="utf-8"?>
<Order>
  <CustomerName>刘XX</CustomerName>
  <OrderNumber>100</OrderNumber>
  <Items>
    <OrderItem1 Name="锅巴" Count="+10" Price="12" />
    <OrderItem2 Name="杯子" Count="6" Price="8" />
  </Items>
</Order>
//输出:锅巴

使用XPath的方式修改XML

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace _08AlterXMLWithXPath
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("Order.xml");
            //获得根节点
            XmlElement order = doc.DocumentElement;
            XmlNode xn = order.SelectSingleNode("/Order/Items/OrderItem1[@Name='锅巴']");
            //Console.WriteLine(xn.Attributes["Name"].Value);
            //修改
            xn.Attributes["Count"].Value = "又+10";
            doc.Save("Order.xml");
            Console.WriteLine("保存成功!");
            Console.ReadKey();
        }
    }
}
//XML:
<?xml version="1.0" encoding="utf-8"?>
<Order>
  <CustomerName>刘XX</CustomerName>
  <OrderNumber>100</OrderNumber>
  <Items>
    <OrderItem1 Name="锅巴" Count="又+10" Price="12" />
    <OrderItem2 Name="杯子" Count="6" Price="8" />
  </Items>
</Order>

使用XPath的方式删除XML

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace _09DeleteXMLWithXPath
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("Order.xml");
            // doc.RemoveAll();//不行,根节点不允许删除
            XmlElement order = doc.DocumentElement;
            //order.RemoveAll();//移除根节点下的所有子节点
            XmlNode xn = order.SelectSingleNode("/Order/Items/OrderItem[@Name='锅巴']");
            //orderItem删除属性
            XmlNode orderItem = order.SelectSingleNode("/Order/Items/OrderItem");
            //获得items节点
            XmlNode items = order["Items"];//或者order.SelectSingleNode("/Order/Items");
            items.RemoveChild(xn);//移除当前节点(锅巴)
            //删除杯子的Count属性
            XmlNode xn1 = order.SelectSingleNode("/Order/Items/OrderItem[@Name='杯子']");
            xn1.Attributes.RemoveNamedItem("Count");
            doc.Save("Order.xml");
            Console.WriteLine("删除成功!");
            Console.ReadKey();  
        }
    }
}
//XML:
<?xml version="1.0" encoding="utf-8"?>
<Order>
  <CustomerName>刘XX</CustomerName>
  <OrderNumber>100</OrderNumber>
  <Items>
    <OrderItem Name="杯子" Price="8" />
  </Items>
</Order>
posted @ 2019-11-28 23:33  爱学习的刘某某  阅读(106)  评论(0编辑  收藏  举报