C#操作XML方法集合

C#操作XML方法集合先来了解下操作XML所涉及到的几个类及之间的关系如果大家发现少写了一些常用的方法,麻烦在评论中指出,我一定会补上的!谢谢大家*1XMLElement主要是针对节点的一些属性进行操作

大家好,又见面了,我是你们的朋友全栈君。

 

一 前言

先来了解下操作XML所涉及到的几个类及之间的关系  如果大家发现少写了一些常用的方法,麻烦在评论中指出,我一定会补上的!谢谢大家

* 1 XMLElement 主要是针对节点的一些属性进行操作
* 2 XMLDocument 主要是针对节点的CUID操作
* 3 XMLNode 为抽象类,做为以上两类的基类,提供一些操作节点的方法

 

 

<span role="heading" aria-level="2">C#操作XML方法集合

清楚了以上的关系在操作XML时会更清晰一点

 

二 具体操作(C#)

  以下会对Xml的结点与属性做增 删 改 查的操作也满足了实际工作中的大部分情况 

先构造一棵XML树如下,其中也涉及到了写入xml文档的操作

 

 1         public void CreatXmlTree(string xmlPath)
 2         {
 3             XElement xElement = new XElement(
 4                 new XElement("BookStore",
 5                     new XElement("Book",
 6                         new XElement("Name", "C#入门", new XAttribute("BookName", "C#")),
 7                         new XElement("Author", "Martin", new XAttribute("Name", "Martin")),
 8                         new XElement("Adress", "上海"),
 9                         new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"))
10                         ),
11                     new XElement("Book",
12                         new XElement("Name", "WCF入门", new XAttribute("BookName", "WCF")),
13                         new XElement("Author", "Mary", new XAttribute("Name", "Mary")),
14                         new XElement("Adress", "北京"),
15                         new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"))
16                         )
17                         )
18                 );
19 
20             //需要指定编码格式,否则在读取时会抛:根级别上的数据无效。 第 1 行 位置 1异常
21             XmlWriterSettings settings = new XmlWriterSettings();
22             settings.Encoding = new UTF8Encoding(false);
23             settings.Indent = true;
24             XmlWriter xw = XmlWriter.Create(xmlPath,settings);
25             xElement.Save(xw);
26             //写入文件
27             xw.Flush();
28             xw.Close();
29         }

 

然后得到如下的XML树

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <BookStore>
 3     <Book>
 4         <Name BookName="C#">C#入门</Name>
 5         <Author Name="Martin">Martin</Author>
 6         <Date>2013-10-11</Date>
 7         <Adress>上海</Adress>
 8         <Date>2013-10-11</Date>
 9     </Book>
10     <Book>
11         <Name BookName="WCF">WCF入门</Name>
12         <Author Name="Mary">Mary</Author>
13         <Adress>北京</Adress>
14         <Date>2013-10-11</Date>
15     </Book>
16 </BookStore>

 

以下操作都是对生成的XML树进行操作

2.1 新增节点与属性

新增节点NewBook并增加属性Name=”WPF”

 1         public void Create(string xmlPath)
 2         {
 3             XmlDocument xmlDoc = new XmlDocument();
 4             xmlDoc.Load(xmlPath);
 5             
 6             var root = xmlDoc.DocumentElement;//取到根结点
 7             XmlNode newNode = xmlDoc.CreateNode("element", "NewBook", "");
 8             newNode.InnerText = "WPF";
 9 
10             //添加为根元素的第一层子结点
11             root.AppendChild(newNode);
12             xmlDoc.Save(xmlPath);
13         }

 

 开篇有写操作xml节点属性主要用XmlElement对象所以取到结点后要转类型 

 1         //属性
 2         public void CreateAttribute(string xmlPath)
 3         {
 4             XmlDocument xmlDoc = new XmlDocument();
 5             xmlDoc.Load(xmlPath);
 6             var root = xmlDoc.DocumentElement;//取到根结点
 7             XmlElement node = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
 8             node.SetAttribute("Name", "WPF");
 9             xmlDoc.Save(xmlPath);
10 
11         }

 

 效果如下

<span role="heading" aria-level="2">C#操作XML方法集合

 

2.2 删除节点与属性

 1         public void Delete(string xmlPath)
 2         {
 3             XmlDocument xmlDoc = new XmlDocument();
 4             xmlDoc.Load(xmlPath);
 5             var root = xmlDoc.DocumentElement;//取到根结点
 6 
 7             var element = xmlDoc.SelectSingleNode("BookStore/NewBook");
 8             root.RemoveChild(element);
 9             xmlDoc.Save(xmlPath);
10         }

删除属性

 1         public void DeleteAttribute(string xmlPath)
 2         {
 3             XmlDocument xmlDoc = new XmlDocument();
 4             xmlDoc.Load(xmlPath);
 5             XmlElement node = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
 6             //移除指定属性
 7             node.RemoveAttribute("Name");
 8             //移除当前节点所有属性,不包括默认属性
 9             //node.RemoveAllAttributes();
10             xmlDoc.Save(xmlPath);
11         }

 

2.3 修改节点与属性

   xml的节点默认是不允许修改的,本文也就不做处理了

  修改属性代码如下

1         public void ModifyAttribute(string xmlPath)
2         {
3             XmlDocument xmlDoc = new XmlDocument();
4             xmlDoc.Load(xmlPath);
5             XmlElement element = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
6             element.SetAttribute("Name", "Zhang");
7             xmlDoc.Save(xmlPath);
8         }

效果如下

<span role="heading" aria-level="2">C#操作XML方法集合

2.4 获取节点与属性

 1         public void Select(string xmlPath)
 2         {
 3             XmlDocument xmlDoc = new XmlDocument();
 4             xmlDoc.Load(xmlPath);
 5             //取根结点
 6             var root = xmlDoc.DocumentElement;//取到根结点
 7             //取指定的单个结点
 8             XmlNode oldChild = xmlDoc.SelectSingleNode("BookStore/NewBook");
 9             
10             //取指定的结点的集合
11             XmlNodeList nodes = xmlDoc.SelectNodes("BookStore/NewBook");
12 
13             //取到所有的xml结点
14             XmlNodeList nodelist = xmlDoc.GetElementsByTagName("*");
15         }

属性

1         public void SelectAttribute(string xmlPath)
2         {
3             XmlDocument xmlDoc = new XmlDocument();
4             xmlDoc.Load(xmlPath);
5             XmlElement element = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
6             string name = element.GetAttribute("Name");
7             Console.WriteLine(name);
8         }

 

 

三  具体操作 (linq to XML)

 Linq to Xml 也没什么变化只操作对象改变了主要涉及的几个对象如下   注:我并没有用linq的语法去操作元素

XDocument:用于创建一个XML实例文档

XElement:用于一些节点与节点属性的基本操作

以下是对Xml的 一些简单的操作

3.1 新增节点与属性

1         public void Create(string xmlPath)
2         {
3             XDocument xDoc = XDocument.Load(xmlPath);
4             XElement xElement = xDoc.Element("BookStore");
5             xElement.Add(new XElement("Test", new XAttribute("Name", "Zery")));
6             xDoc.Save(xmlPath);
7         }

属性

 1         public void CreateAttribute(string xmlPath)
 2         {
 3             XDocument xDoc = XDocument.Load(xmlPath);
 4             IEnumerable<XElement> xElement = xDoc.Element("BookStore").Elements("Book");
 5             foreach (var element in xElement)
 6             {
 7                 element.SetAttributeValue("Name", "Zery");
 8             }
 9             xDoc.Save(xmlPath);
10         }

 

3.2 删除节点与属性

1         public void Delete(string xmlPath)
2         {
3             XDocument xDoc = XDocument.Load(xmlPath);
4             XElement element = (XElement)xDoc.Element("BookStore").Element("Book");
5             element.Remove();
6             xDoc.Save(xmlPath);
7         }

属性

1         public void DeleteAttribute(string xmlPath)
2         {
3             XDocument xDoc = XDocument.Load(xmlPath);
4             //不能跨级取节点
5             XElement element = xDoc.Element("BookStore").Element("Book").Element("Name");
6             element.Attribute("BookName").Remove();
7             xDoc.Save(xmlPath);
8         }

3.3 修改节点属性

节点.net没提供修改的方法本文也不做处理

修改属性与新增实质是同一个方法

1         public void ModifyAttribute(string xmlPath)
2         {
3             XDocument xDoc = XDocument.Load(xmlPath);
4             XElement element = xDoc.Element("BookStore").Element("Book");
5             element.SetAttributeValue("BookName","ZeryTest");
6             xDoc.Save(xmlPath);
7         }

 

 四 总结

  把文章写完时,又扫去了自己的一个盲区,虽然都是些简单的操作,但在实际的开中,又何尝不是由简单到复杂呢。我觉得身为程序员就应该遇到自己的盲区时,立马花时间去了解,不说要了解多深入,但至少基本的还是要知道,等到工作中真需时,只要稍微花点时间就可以了。

如果觉得文章对你有点帮助,不妨点下推荐,你的推荐让我对写文章能有更多的激情!

成长在于积累!

 

Demo 源码

<span role="heading" aria-level="2">C#操作XML方法集合
<span role="heading" aria-level="2">C#操作XML方法集合

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

namespace XMLOperation
{
    class Program
    {
        static void Main(string[] args)
        {
            /*=============Linq 读写XML==================*/
            string wxmlPath = @"F:\XmlTest\test.xml";
            XmlWriteReadLinqOperation writeReadLinq = new XmlWriteReadLinqOperation();
            // writeReadLinq.WriteXml(wxmlPath);
            writeReadLinq.CreatXmlTree(wxmlPath);




            //string xmlPath = @"F:\XML.xml";
            string xmlPath = @"C:\Users\zery.zhang\Desktop\ProjectDemo\XML.xml";
            /*
             * 1 三者之间的关系用图画出
             * 2 XMLElement 主要是针对节点的一些属性进行操作
             * 3 XMLDocument 主要是针对节点的CUID操作
             * 4 XMLNode 为抽象类,做为以上两类的基类,提供一些操作节点的方法 
             */

            //===========C# to Xml==========//
            XmlOperation xmlOperation = new XmlOperation();
            //xmlOperation.Create(xmlPath);
            //xmlOperation.CreateAttribute(xmlPath);

            //xmlOperation.Delete(xmlPath);
            //xmlOperation.DeleteAttribute(xmlPath);

            //xmlOperation.Modify(xmlPath);
            //xmlOperation.ModifyAttribute(xmlPath);

            //xmlOperation.Select(xmlPath);
            //xmlOperation.SelectAttribute(xmlPath);
            /*=============Linq to Xml===========*/
            XmlOperationToLinq xOperation = new XmlOperationToLinq();
            // xOperation.Create(xmlPath);
            /*
             *1 给指定的XML节点的所有子节点增加一个节点,并增加属性
             *2 删除指定节点的子节点的指定属性
             *3 
             */
            string lxmlPath = @"F:\XmlTest\test.xml";
            xOperation.Create(lxmlPath);
            xOperation.CreateAttribute(lxmlPath);
            //xperation.Delete(lxmlPath);
            //xOperation.DeleteAttribute(lxmlPath);
           // xOperation.ModifyAttribute(lxmlPath);

            /*=============C# 读写XML===============*/
            XmlWriteReadOperation writeRead = new XmlWriteReadOperation();


            Console.Read();

        }

    }

    class XmlOperation
    {

        public void Create(string xmlPath)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlPath);
            var root = xmlDoc.DocumentElement;//取到根结点

            XmlNode newNode = xmlDoc.CreateNode("element", "Name", "");
            newNode.InnerText = "Zery";

            //添加为根元素的第一层子结点
            root.AppendChild(newNode);
            xmlDoc.Save(xmlPath);
        }
        //属性
        public void CreateAttribute(string xmlPath)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlPath);
            XmlElement node = (XmlElement)xmlDoc.SelectSingleNode("Collection/Book");
            node.SetAttribute("Name", "C#");
            xmlDoc.Save(xmlPath);
        }

        public void Delete(string xmlPath)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlPath);
            var root = xmlDoc.DocumentElement;//取到根结点

            var element = xmlDoc.SelectSingleNode("Collection/Name");
            root.RemoveChild(element);
            xmlDoc.Save(xmlPath);
        }

        public void DeleteAttribute(string xmlPath)
        {
            
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlPath);
            XmlElement node = (XmlElement)xmlDoc.SelectSingleNode("Collection/Book");
            //移除指定属性
            node.RemoveAttribute("Name");
            //移除当前节点所有属性,不包括默认属性
            node.RemoveAllAttributes();

            xmlDoc.Save(xmlPath);

        }

        public void Modify(string xmlPath)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlPath);
            var root = xmlDoc.DocumentElement;//取到根结点
            XmlNodeList nodeList = xmlDoc.SelectNodes("/Collection/Book");
            //xml不能直接更改结点名称,只能复制然后替换,再删除原来的结点
            foreach (XmlNode node in nodeList)
            {
                var xmlNode = (XmlElement)node;
                xmlNode.SetAttribute("ISBN", "Zery");
            }
            xmlDoc.Save(xmlPath);

        }

        public void ModifyAttribute(string xmlPath)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlPath);
            XmlElement element = (XmlElement)xmlDoc.SelectSingleNode("Collection/Book");
            element.SetAttribute("Name", "Zhang");
            xmlDoc.Save(xmlPath);

        }

        public void Select(string xmlPath)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlPath);
            //取根结点
            var root = xmlDoc.DocumentElement;//取到根结点
            //取指定的单个结点
            XmlNode singleNode = xmlDoc.SelectSingleNode("Collection/Book");

            //取指定的结点的集合
            XmlNodeList nodes = xmlDoc.SelectNodes("Collection/Book");

            //取到所有的xml结点
            XmlNodeList nodelist = xmlDoc.GetElementsByTagName("*");
        }

        public void SelectAttribute(string xmlPath)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlPath);
            XmlElement element = (XmlElement)xmlDoc.SelectSingleNode("Collection/Book");
            string name = element.GetAttribute("Name");
          
        }
    }

    class XmlOperationToLinq
    {
        //其它操作
        public void OtherOperaton()
        {
            //加文件头
        }



        public void Create(string xmlPath)
        {
            XDocument xDoc = XDocument.Load(xmlPath);
            XElement xElement = xDoc.Element("BookStore");
            xElement.Add(new XElement("Test", new XAttribute("Name", "Zery")));
            xDoc.Save(xmlPath);
        }

        public void CreateAttribute(string xmlPath)
        {
            XDocument xDoc = XDocument.Load(xmlPath);
            IEnumerable<XElement> xElement = xDoc.Element("BookStore").Elements("Book");
            foreach (var element in xElement)
            {
                element.SetAttributeValue("Name", "Zery");
            }
            xDoc.Save(xmlPath);
        }
        
        public void Delete(string xmlPath)
        {
            XDocument xDoc = XDocument.Load(xmlPath);
            XElement element = (XElement)xDoc.Element("BookStore").Element("Book");
            element.Remove();
            xDoc.Save(xmlPath);
        }

        public void DeleteAttribute(string xmlPath)
        {
            XDocument xDoc = XDocument.Load(xmlPath);
            //不能跨级取节点
            XElement element = xDoc.Element("BookStore").Element("Book").Element("Name");
            element.Attribute("BookName").Remove();
            xDoc.Save(xmlPath);
        }

        public void ModifyAttribute(string xmlPath)
        {
            XDocument xDoc = XDocument.Load(xmlPath);
            XElement element = xDoc.Element("BookStore").Element("Book");
            element.SetAttributeValue("BookName","ZeryTest");
            xDoc.Save(xmlPath);
        }


    }

    internal class XmlWriteReadOperation
    {

    }


    class XmlWriteReadLinqOperation
    {


        public void CreatXmlTree(string xmlPath)
        {
            XElement xElement = new XElement(
                new XElement("BookStore",
                    new XElement("Book",
                        new XElement("Name", "C#入门", new XAttribute("BookName", "C#")),
                        new XElement("Author", "Martin", new XAttribute("Name", "Martin")),
                        new XElement("Adress", "上海"),
                        new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"))
                        ),
                    new XElement("Book",
                        new XElement("Name", "WCF入门", new XAttribute("BookName", "WCF")),
                        new XElement("Author", "Mary", new XAttribute("Name", "Mary")),
                        new XElement("Adress", "北京"),
                        new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"))
                        )
                        )
                );

            //需要指定编码格式,否则在读取时会抛:根级别上的数据无效。 第 1 行 位置 1异常
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Encoding = new UTF8Encoding(false);
            settings.Indent = true;
            XmlWriter xw = XmlWriter.Create(xmlPath,settings);
            xElement.Save(xw);
            //写入文件
            xw.Flush();
            xw.Close();
        }




        public void WriteXml(string xmlPath)
        {
            XElement xElement = new XElement(
                new XElement("Store",
                    new XElement("Book", "技术类",
                        new XElement("Name", "C#入门", new XAttribute("BookName", "C#")),
                        new XElement("Author", "Martin", new XAttribute("Name", "Zery")),
                        new XComment("以下为注释"),//xml注释
                        new XElement("Date", DateTime.Now.ToString(), new XAttribute("PublicDate", DateTime.Now.ToString()))
                        ))
                );
       
            XmlWriter xw = XmlWriter.Create(xmlPath);
            //保存到XmlWriter
            xElement.Save(xw);
            //写入文件
            xw.Flush();
            xw.Close();

        }


    }
}

View Code

 

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/154253.html原文链接:https://javaforall.net

(0)
上一篇 2022年6月30日 下午8:46
下一篇 2022年6月30日 下午8:46


相关推荐

  • css 半透明滚动条「建议收藏」

    css 半透明滚动条「建议收藏」::-webkit-scrollbar{width:10px;height:10px;}::-webkit-scrollbar-thumb{background:hsl(0,0%,51%);-webkit-box-shadow:none;border-radius:10px;-webkit-box-shadow:none;}::-webki…

    2022年7月13日
    17
  • 谱图理论(spectral graph theory)

    谱图理论(spectral graph theory)介绍如何理解特征值和特征向量此部分参考了马同学的文章:如何理解矩阵特征值和特征向量?我们知道一个矩阵可以看做是线性变换又或者是某种运动,可以将一个向量进行旋转,平移等等操作,正常来说,对于一个向量vvv,并对其乘上一个A会出现下图的情况:可以看到乘了A之后v发生了一些旋转。然而所有向量中存在一种稳定的向量,他不会发生旋转,平移,只会使得向量变长或变短,而这种稳定的向量正是矩阵的特征向…

    2025年6月6日
    4
  • https 证书工具 Letsencrypt 简单教程

    https 证书工具 Letsencrypt 简单教程https 取代 http 是大势所趋 https 的好处本文不在赘述 很多公司和机构都在推进这一进程 Apple 公司甚至规定 iOS 上的 App 应用必须使用 https 因此 正是受到 Apple 的限制 我们的站点 几乎是所有的站点 接近上百个 都支持了 https nbsp 如何获取 SSL 证书 自签名证书我们可以自己为自己颁发 SSL 证书 这样的证书满足为 http 加密的要求 但这样的证书缺少权威性 不会被浏

    2026年3月18日
    2
  • OpenSearch 简单学习

    OpenSearch 简单学习OpenSearch 简单学习项目中用到了阿里云的开放搜索 进行一下总结 OpenSearch 基于阿里巴巴自主研发的大规模分布式搜索引擎平台 该平台承载了阿里巴巴全部主要搜索业务 包括淘宝 天猫 一淘 1688 ICBU 神马搜索等业务 OpenSearch 以平台服务化的形式 将专业搜索技术简单化 低门槛化和低成本化 让搜索引擎技术不再成为客户的业务瓶颈 以低成本实现产品搜索功能并快速迭代

    2025年7月5日
    10
  • 完全教程 Aircrack-ng

    完全教程 Aircrack-ng网页地图贴吧应用更多新闻知道百科图片小说文库音乐视频 aircrack 百度一下您可以仅查看 英文结果完全教程 Aircrack ng 激活成功教程 WEP WPA PSK 加密利器 51 2011 年 5 月 26 日 nbsp nbsp 步骤 5 打开 aircrack ng 开始激活成功教程 WEP

    2026年3月18日
    2
  • vue 路由守卫 解析

    vue 路由守卫 解析路由跳转有两种方式 1 方式 2 编程式跳转 路由守卫控制路由在符合某种条件下才能完成跳转 后置 在跳转之后判断 不管符不符合 路由都会跳转 浏览器地址栏都会变化 多用于跳转后修改页签标题等 中 亦或者是在与某个引入了 src router index js 文件暴露的 router 的 前置 在路由切换之前判断 不符合条件则不跳转 to 要去的路由 from 当前路由 next 触发跳转 to 要去的路由 from 当前路由 next 触发跳转 1 全局前置路由守卫

    2026年3月16日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号