C# 五十三、C#中使用XML

创建XML文件:

解决方案 --->项目(命名空间)--右击 -->添加/新建项 ---> XML文件

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<books>
  <book s="悲">
    <name>红楼梦</name>
    <price>100</price>
    <author>曹雪芹</author>
  </book>
  <book s="谋">
    <name>三国演义</name>
    <price>100</price>
    <author>罗贯中</author>
  </book>
  <book s="佛">
    <name>西游记</name>
    <price>100</price>
    <author>吴承恩</author>
  </book>
  <book s="闹">
    <name>水浒传</name>
    <price>100</price>
    <author>施耐庵</author>
  </book>
</books>

代码完成创建与编辑:

(下面代码不是同一时间同一项目下完成,所以路径不同,请自行调整)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Xml;

namespace Test_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            //1 引入命名空间
            //2 建立Xml文档对象
            XmlDocument doc = new XmlDocument();
            //3 创建Xml第一行的描述信息
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", "yes");
            doc.AppendChild(dec);
            //4 创建根节点 并添加
            XmlElement books = doc.CreateElement("books");
            doc.AppendChild(books);
            //5 创建books子节点 并添加
            XmlElement book1 = doc.CreateElement("book");
            books.AppendChild(book1);

            //6 创建book子节点 并添加
            XmlElement name1 = doc.CreateElement("name");
            book1.AppendChild(name1);
            name1.InnerText = "红楼梦";
            XmlElement price1 = doc.CreateElement("price");
            book1.AppendChild(price1);
            price1.InnerText = "100";
            XmlElement author1 = doc.CreateElement("author");
            book1.AppendChild(author1);
            author1.InnerText = "曹雪芹";

            XmlElement book2 = doc.CreateElement("book");
            books.AppendChild(book2);
            XmlElement name2 = doc.CreateElement("name");
            book2.AppendChild(name2);
            name2.InnerText = "三国演义";
            XmlElement price2 = doc.CreateElement("price");
            book2.AppendChild(price2);
            price2.InnerText = "100";
            XmlElement author2 = doc.CreateElement("author");
            book2.AppendChild(author2);
            author2.InnerText = "罗贯中";

            XmlElement book3 = doc.CreateElement("book");
            books.AppendChild(book3);
            XmlElement name3 = doc.CreateElement("name");
            book3.AppendChild(name3);
            name3.InnerText = "西游记";
            XmlElement price3 = doc.CreateElement("price");
            book3.AppendChild(price3);
            price3.InnerText = "100";
            XmlElement author3 = doc.CreateElement("author");
            book3.AppendChild(author3);
            author3.InnerText = "吴承恩";

            XmlElement book4 = doc.CreateElement("book");
            books.AppendChild(book4);
            XmlElement name4 = doc.CreateElement("name");
            book4.AppendChild(name4);
            name4.InnerText = "水浒传";
            XmlElement price4 = doc.CreateElement("price");
            book4.AppendChild(price4);
            price4.InnerText = "100";
            XmlElement author4 = doc.CreateElement("author");
            book4.AppendChild(author4);
            author4.InnerText = "施耐庵";

            //设置子节点属性
            //方法一:
            book1.SetAttribute("s", "悲");
            book2.SetAttribute("s", "谋");
            book3.SetAttribute("s", "佛");
            book4.SetAttribute("s", "闹");
            //方法二:
            //XmlAttribute xmlAttribute = doc.CreateAttribute("s");
            //xmlAttribute.Value = "悲";
            //book1.Attributes.Append(xmlAttribute);

            //存储为文件
            doc.Save("SDMZ.XML");
        }
    }   
}

获取信息并遍历:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Xml;

namespace Test_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            //判断文件是否存在
            bool isb = File.Exists(@"C:\Users\86515\Desktop\Shu.XML");
            if (isb)
            {
                //加载文件
                XmlDocument doc = new XmlDocument();
                doc.Load(@"C:\Users\86515\Desktop\Shu.XML");

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

                //获取根节点下的所有子节点                
                XmlNodeList list = books.ChildNodes;
                foreach (XmlElement item in list)
                {
                    Console.WriteLine(item.Name);
                    Console.WriteLine(item.GetAttribute("s"));
                    XmlNodeList nod = item.ChildNodes;
                    foreach (XmlElement ite in nod)
                    {
                        Console.WriteLine(ite.InnerText);
                    }
                }
            }

            Console.ReadKey();
        }
    }
}

--->
book
悲
红楼梦
100
曹雪芹
book
谋
三国演义
100
罗贯中
book
佛
西游记
100
吴承恩
book
闹
水浒传
100
施耐庵

查找获取节点: 

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

namespace Test_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            //建立Xml文档对象
            XmlDocument xmlDoc = new XmlDocument();
            //加载文件
            xmlDoc.Load("Test.xml");

            //XmlElement xmlElement1 = xmlDoc.LastChild as XmlElement;//最后的节点
            //XmlElement xmlElement2 = xmlElement1.FirstChild as XmlElement;//第一个节点

            Console.WriteLine("查找单个节点");
            XmlElement node = xmlDoc.SelectSingleNode("books/book") as XmlElement;
            Console.WriteLine(node.GetAttribute("s"));
            Console.WriteLine("-----");

            Console.WriteLine("查找多个节点");
            XmlNodeList nodes = xmlDoc.SelectNodes("books/book/name");//绝对路径
            //XmlNodeList nodes = xmlDoc.SelectNodes("//name");//相对路径           
            foreach (XmlElement item in nodes)
            {
                Console.WriteLine(item.InnerText);
            }
            Console.WriteLine("-----");

            Console.WriteLine("获取指定位置的节点");
            Console.WriteLine("获取第一个");
            XmlNodeList theNodes1 = xmlDoc.SelectNodes("//book[1]/name");
            foreach (XmlElement item in theNodes1)
            {
                Console.WriteLine(item.InnerText);
            }
            Console.WriteLine("-----");
            Console.WriteLine("获取倒数第二个");
            XmlNodeList theNodes2 = xmlDoc.SelectNodes("//book[last()-1]/name");
            foreach (XmlElement item in theNodes2)
            {
                Console.WriteLine(item.InnerText);
            }
            Console.WriteLine("-----");
            Console.WriteLine("获取前两个");
            XmlNodeList theNodes3 = xmlDoc.SelectNodes("//book[position()<3]/name");
            foreach (XmlElement item in theNodes3)
            {
                Console.WriteLine(item.InnerText);
            }
            Console.WriteLine("-----");

            Console.WriteLine("获取指定属性的节点");
            Console.WriteLine("获取具有s属性的节点");
            XmlNodeList theNodes4 = xmlDoc.SelectNodes("//book[@s]/name");
            foreach (XmlElement item in theNodes4)
            {
                Console.WriteLine(item.InnerText);
            }
            Console.WriteLine("-----");
            Console.WriteLine("获取具有s属性,且属性值为“谋”的节点");
            XmlNodeList theNodes5 = xmlDoc.SelectNodes("//book[@s='谋']/name");//获取具有s属性,且属性值为“谋”的节点
            foreach (XmlElement item in theNodes5)
            {
                Console.WriteLine(item.InnerText);
            }
            Console.WriteLine("-----");

            Console.ReadKey();
        }
    }
}

--->
查找单个节点
悲
-----
查找多个节点
红楼梦
三国演义
西游记
水浒传
-----
获取指定位置的节点
获取第一个
红楼梦
-----
获取倒数第二个
西游记
-----
获取前两个
红楼梦
三国演义
-----
获取指定属性的节点
获取具有s属性的节点
红楼梦
三国演义
西游记
水浒传
-----
获取具有s属性,且属性值为“谋”的节点
三国演义
-----

通过标签查找 

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

namespace TestXML
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load("XMLFile1.xml");

            XmlElement root = xmlDoc.LastChild as XmlElement;

            foreach (XmlElement item in root)
            {
                Console.WriteLine(item.GetElementsByTagName("name")[0].InnerText);
            }

            Console.ReadKey();
        }
    }
}

--->
红楼梦
三国演义
西游记
水浒传

添加一个节点:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Xml;

namespace Test_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            //建立Xml文档对象
            XmlDocument xmlDoc = new XmlDocument();
            //加载文件
            xmlDoc.Load("SDMZ.XML");
            //查找根节点<books>
            XmlNode root = xmlDoc.SelectSingleNode("books");
            //创建一个<A>节点
            XmlElement A = xmlDoc.CreateElement("A");
            //设置该节点属性
            A.SetAttribute("aa", "AA");
            A.SetAttribute("aaa", "AAA");
            //创建一个<a>节点
            XmlElement a = xmlDoc.CreateElement("a");
            //设置文本节点
            a.InnerText = "a";
            //添加a到<A>节点中
            A.AppendChild(a);
            //添加到<Employees>节点中
            root.AppendChild(A);
            //保持文件
            xmlDoc.Save("SDMZ.XML");

            Console.ReadKey();
        }
    }   
}
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<books>
  <book s="悲">
    <name>红楼梦</name>
    <price>100</price>
    <author>曹雪芹</author>
  </book>
  <book s="谋">
    <name>三国演义</name>
    <price>100</price>
    <author>罗贯中</author>
  </book>
  <book s="佛">
    <name>西游记</name>
    <price>100</price>
    <author>吴承恩</author>
  </book>
  <book s="闹">
    <name>水浒传</name>
    <price>100</price>
    <author>施耐庵</author>
  </book>
  <Node aa="AA" aaa="AAA">
    <a>a</a>
  </Node>
  <A aa="AA" aaa="AAA">
    <a>a</a>
  </A>
</books>

修改节点的值(属性和子节点):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Xml;

namespace Test_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            //建立Xml文档对象
            XmlDocument xmlDoc = new XmlDocument();
            //加载文件
            xmlDoc.Load("SDMZ.XML");
            //查找根节点<books>的所有子节点
            XmlNodeList nodeList = xmlDoc.SelectSingleNode("books").ChildNodes;
            //遍历books所有子节点
            foreach (XmlNode book in nodeList)
            {
                //将子节点类型转换为XmlElement类型
                XmlElement boo = (XmlElement)book;
                //如果属性值为“AA”
                if (boo.GetAttribute("aa") == "AA")
                {
                    //则修改该属性为“啊啊”
                    boo.SetAttribute("aa", "啊啊");

                    //继续获取boo子节点的所有子节点
                    XmlNodeList bo = boo.ChildNodes;
                    //遍历boo所有子节点
                    foreach (XmlNode b in bo)
                    {
                        //转换类型
                        XmlElement bb = (XmlElement)b;
                        //如果找到
                        if (bb.Name == "a")
                        {
                            //则修改
                            bb.InnerText = "啊";
                        }
                    }
                }
            }

            //保存文件
            xmlDoc.Save("SDMZ.XML");
        }
    }   
}
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<books>
  <book s="悲">
    <name>红楼梦</name>
    <price>100</price>
    <author>曹雪芹</author>
  </book>
  <book s="谋">
    <name>三国演义</name>
    <price>100</price>
    <author>罗贯中</author>
  </book>
  <book s="佛">
    <name>西游记</name>
    <price>100</price>
    <author>吴承恩</author>
  </book>
  <book s="闹">
    <name>水浒传</name>
    <price>100</price>
    <author>施耐庵</author>
  </book>
  <Node aa="啊啊" aaa="AAA">
    <a>啊</a>
  </Node>
</books>

修改节点(添加节点的属性和添加结点的子节点):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Xml;

namespace Test_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            //建立Xml文档对象
            XmlDocument xmlDoc = new XmlDocument();
            //加载文件
            xmlDoc.Load("SDMZ.XML");
            //查找根节点<books>的所有子节点
            XmlNodeList nodeList = xmlDoc.SelectSingleNode("books").ChildNodes;
            //遍历books所有子节点
            foreach (XmlNode book in nodeList)
            {
                //将子节点类型转换为XmlElement类型
                XmlElement boo = (XmlElement)book;
                //如果节点名为“Node”
                if (boo.Name == "Node")
                {
                    //则添加属性为“AAAA”
                    boo.SetAttribute("aaaa", "AAAA");
                    //创建节点
                    XmlElement bo = xmlDoc.CreateElement("b");
                    //添加文本
                    bo.InnerText = "b";
                    //添加到对应节点中作为子节点
                    boo.AppendChild(bo);
                }
            }

            //保存文件
            xmlDoc.Save("SDMZ.XML");
        }
    }   
}
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<books>
  <book s="悲">
    <name>红楼梦</name>
    <price>100</price>
    <author>曹雪芹</author>
  </book>
  <book s="谋">
    <name>三国演义</name>
    <price>100</price>
    <author>罗贯中</author>
  </book>
  <book s="佛">
    <name>西游记</name>
    <price>100</price>
    <author>吴承恩</author>
  </book>
  <book s="闹">
    <name>水浒传</name>
    <price>100</price>
    <author>施耐庵</author>
  </book>
  <Node aa="啊啊" aaa="AAA" aaaa="AAAA">
    <a>啊</a>
    <b>b</b>
  </Node>
</books>

删除属性和节点

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Xml;

namespace Test_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            //建立Xml文档对象
            XmlDocument xmlDoc = new XmlDocument();
            //加载文件
            xmlDoc.Load("SDMZ.XML");
            //查找根节点<books>的所有子节点
            XmlNodeList nodeList = xmlDoc.SelectSingleNode("books").ChildNodes;
            //遍历books所有子节点
            foreach (XmlNode book in nodeList)
            {
                //将子节点类型转换为XmlElement类型
                XmlElement boo = (XmlElement)book;
                //如果节点名为“Node”
                if (boo.Name == "Node")
                {
                    //如果节点包含此属性
                    if (boo.HasAttribute("aaaa"))
                    {
                        //则删除此属性
                        boo.RemoveAttribute("aaaa");
                    }

                    //遍历Node所有子节点
                    foreach (XmlNode bo in boo)
                    {
                        //找到要删除的节点
                        if (bo.Name == "b")
                        {
                            //删除此节点
                            boo.RemoveChild(bo);
                        }
                    }
                }
            }

            //保存文件
            xmlDoc.Save("SDMZ.XML");
        }
    }   
}
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<books>
  <book s="悲">
    <name>红楼梦</name>
    <price>100</price>
    <author>曹雪芹</author>
  </book>
  <book s="谋">
    <name>三国演义</name>
    <price>100</price>
    <author>罗贯中</author>
  </book>
  <book s="佛">
    <name>西游记</name>
    <price>100</price>
    <author>吴承恩</author>
  </book>
  <book s="闹">
    <name>水浒传</name>
    <price>100</price>
    <author>施耐庵</author>
  </book>
  <Node aa="啊啊" aaa="AAA">
    <a>啊</a>
  </Node>
</books>

解析具有命名空间的XML文件

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<books xmlns:A="http://microsoft.com/schemas/VisualStudio/TeamTest/2010" xmlns:B="http://schemas.microsoft.com/ado/2006/04/codegeneration">
  <book s="悲">
    <A:name>红楼梦</A:name>
    <B:name>石头记</B:name>
    <price>100</price>
    <author>曹雪芹</author>
  </book>
  <book s="谋">
    <name>三国演义</name>
    <price>100</price>
    <author>罗贯中</author>
  </book>
  <book s="佛">
    <name>西游记</name>
    <price>100</price>
    <author>吴承恩</author>
  </book>
  <book s="闹">
    <name>水浒传</name>
    <price>100</price>
    <author>施耐庵</author>
  </book>
</books>
using LitJson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Test_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Read();
            Console.ReadKey();
        }

        static void Read()
        {
            //建立Xml文档对象
            XmlDocument xmlDoc = new XmlDocument();
            //加载文件
            xmlDoc.Load("SDMZ.XML");
            //创建名称空间管理器类
            XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(xmlDoc.NameTable);
            //添加一个名称空间映射
            xmlNamespaceManager.AddNamespace("B", "http://schemas.microsoft.com/ado/2006/04/codegeneration");
            //xpath解析
            XmlNodeList xmlNodeList = xmlDoc.SelectNodes("books/book/B:name", xmlNamespaceManager);
            foreach (XmlElement item in xmlNodeList)
            {
                Console.WriteLine(item.InnerText);
            }
        }
    }
}

--->
石头记
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<books xmlns:A="http://microsoft.com/schemas/VisualStudio/TeamTest/2010" xmlns:B="http://schemas.microsoft.com/ado/2006/04/codegeneration" xmlns="http://schemas.microsoft.com/ado/2006/04/edm">
  <book s="悲">
    <A:name>红楼梦</A:name>
    <B:name>石头记</B:name>
    <price>100</price>
    <author>曹雪芹</author>
  </book>
  <book s="谋">
    <name>三国演义</name>
    <price>100</price>
    <author>罗贯中</author>
  </book>
  <book s="佛">
    <name>西游记</name>
    <price>100</price>
    <author>吴承恩</author>
  </book>
  <book s="闹">
    <name>水浒传</name>
    <price>100</price>
    <author>施耐庵</author>
  </book>
</books>
using LitJson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Test_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Read();
            Console.ReadKey();
        }

        static void Read()
        {
            //建立Xml文档对象
            XmlDocument xmlDoc = new XmlDocument();
            //加载文件
            xmlDoc.Load("SDMZ.XML");
            //创建名称空间管理器类
            XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(xmlDoc.NameTable);

            //含有缺省命名空间时:
            xmlNamespaceManager.AddNamespace("B", "http://schemas.microsoft.com/ado/2006/04/codegeneration");
            xmlNamespaceManager.AddNamespace("default", "http://schemas.microsoft.com/ado/2006/04/edm");
            XmlNodeList xmlNodeList1 = xmlDoc.SelectNodes("default:books/default:book/B:name", xmlNamespaceManager);
            foreach (XmlElement item in xmlNodeList1)
            {
                Console.WriteLine(item.InnerText);
            }
        }
    }
}

--->
石头记

 

按文本文件读取XML

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Xml;

namespace Test_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            //使用System.IO命名空间
            //获取文件信息
            StreamReader myFile = new StreamReader("SDMZ.XML", System.Text.Encoding.Default);
            //读取到字符串
            string myString = myFile.ReadToEnd();
            //关闭流
            myFile.Close();
            //输出读取到的数据
            Console.WriteLine(myString);

            Console.ReadKey();
        }
    }   
}

--->
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<books>
  <book s="悲">
    <name>红楼梦</name>
    <price>100</price>
    <author>曹雪芹</author>
  </book>
  <book s="谋">
    <name>三国演义</name>
    <price>100</price>
    <author>罗贯中</author>
  </book>
  <book s="佛">
    <name>西游记</name>
    <price>100</price>
    <author>吴承恩</author>
  </book>
  <book s="闹">
    <name>水浒传</name>
    <price>100</price>
    <author>施耐庵</author>
  </book>
  <Node aa="啊啊" aaa="AAA">
    <a>啊</a>
  </Node>
</books>

https://www.cnblogs.com/guxia/p/8242483.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值