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

小编 2026-07-13 阅读:771 评论:0
创建XML文件: 解决方案 --->项目(命名空间)--右击 -->添加/新建项 ---> XML文件 <?xml version=\"1.0\" encoding=\"utf...

创建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\", \"闹\");

            //存储为文件
            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(\"SDMZ.XML\");
            if (isb)
            {
                //加载文件
                XmlDocument doc = new XmlDocument();
                doc.Load(\"SDMZ.XML\");

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

                //获取根节点下的所有子节点                
                XmlNodeList list = books.ChildNodes;
                foreach (XmlElement item in list)
                {
                    Console.WriteLine(item.Name);
                    XmlNodeList nod = item.ChildNodes;
                    foreach (XmlElement ite in nod)
                    {
                        Console.WriteLine(ite.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

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

版权声明

本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。

热门文章
  • Sequential Monte Carlo Methods (SMC) 序列蒙特卡洛/粒子滤波/Bootstrap Filtering

    Sequential Monte Carlo Methods (SMC) 序列蒙特卡洛/粒子滤波/Bootstrap Filtering
    Problem Statement 我们考虑一个具有马尔可夫性质、非线性、非高斯的状态空间模型(State Space Model):对于一个时间序列上的观测结果{yt,t∈N}\\{ y_t , t \\in N \\}{yt​,t∈N},我们认为每个观测结果yty_tyt​的生成依赖于一个无法直接观察的隐变量xt∈{xt,t∈N}x_t \\in \\{x_t , t \\in N \\}xt​∈{xt​,t∈N},即:p(...
  • 机房智能化温湿度解决方式之POE供电以太网温湿度传感器

    机房智能化温湿度解决方式之POE供电以太网温湿度传感器
    机房智能化温湿度解决方式之POE供电以太网温湿度传感器 北京盈创力和电子科技有限公司 智能型TCP网口温湿度记录仪 北京IP网络温湿度记录仪厂家,北京盈创力和 北京智能型TCP网口温湿度记录仪IP网络温湿度记录仪是一种新型的基于TCP/IP协议双绞线以太网标准温湿度采集模块,利用它可以实现现场温度值、相对湿度值的采集,同时利用其自身的RJ45通信接口可以方便地和机房监控主机或交换机集线器进行联网。 工作于-40℃~85℃工业级带...
  • Hive 系统函数及示例

    Hive 系统函数及示例
    查看所有系统函数 show functions; 函数分类 内置函数【系统函数】 数学函数: floor、round、ceil、cos、log2等 字符串函数: length、reverse、trim、lower、get_json_object、repeat等 收集函数: size 转换函数: cast 日期函数: year、month、datediff、date、date_add等 条件函数: coalesce、case…w...
  • CSRF的原理和防范措施

    CSRF的原理和防范措施
    a)攻击原理:i.用户C访问正常网站A时进行登录,浏览器保存A的cookieii.用户C再访问攻击网站B,网站B上有某个隐藏的链接或者图片标签会自动请求网站A的URL地址,例如表单提交,传指定的参数iii.而攻击网站B在访问网站A的时候,浏览器会自动带上网站A的cookieiv.所以网站A在接收到请求之后可判断当前用户是登录状态,所以...
  • HTTP状态保持的原理

    HTTP状态保持的原理
    a)在用户登录之后,浏览器返回响应的时候会在响应中添加上cookieb)浏览器接收到cookie之后会自动保存c)当用户再次请求同一服务器中的其他网页的时候,浏览器会自动带上之前保存的cookied)服务接收到请求之后可以请 request 对象中取到cookie 判断当前用户是否登录  Http是无状态的,就是连接时数据互通,关闭后...
标签列表