加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用 linq to xml 操作xml文件

发布时间:2020-12-16 05:00:37 所属栏目:百科 来源:网络整理
导读:今天 使用到了linq操作xml文件,在这里分享一下。 整体 感觉 使用linq to xml 操作xml文件比起使用xmlDocument类而言,开发效率上提高了不少,另外在语法上也精简了很多。 操作之前,需要引入 命名空间 using System.Xml.Linq; xml数据结构无非就是节点(Node

今天 使用到了linq操作xml文件,在这里分享一下。

整体 感觉 使用linq to xml 操作xml文件比起使用xmlDocument类而言,开发效率上提高了不少,另外在语法上也精简了很多。

操作之前,需要引入 命名空间

using System.Xml.Linq;
xml数据结构无非就是节点(Node),再者是节点中的属性(Attribute)。

首先介绍 几个常用类:

XElement : 它就表示一个xml元素,用来加载xml文件,操作xml节点,获取节点下的元素集合(Elements)等。

1.加载Xml文件

string filePath = @"D:a.xml"
private XElement xmlDoc = XElement.Load(filePath);
2.获取某个元素下的node集合

IEnumerable<XElement> elementCollection = xmlDoc.Elements("Group");
Elements 是一个实现IEnumerable接口的集合,集合中的类型也为XElement类型,所以该属性返回的集合为 IEnumerable<XElement>。 这里获取的所有节点名为Group的所有元素。

3.获取某个元素下的Attribute集合

一般的xml文件都会包括节点属性,那么获取节点属性也有对应的方法。

IEnumerable<XAttribute> attributeCollection=elementCollection.Elements("Role").Attributes("Name");
该集合中的类型为XAttribute,表示元素的属性。

4.获取IEnumerable集合中的数据

var  query = from p in  elementCollection select p; 
5.同时获取集合中的元素和元素属性

var  query = from q in elementCollection select new {
p.Element("Name").Value,// 获取元素值
p.Attribute("Tag").Value   // 获取属性值
};
6.将xml字符串转成xml文件。

XElement xml = XElement.Parse("xml字符串");
7.新增元素,修改,保存

 XElement carElement = new XElement("Car",new XAttribute("Id",entity.Id),new XAttribute("Width",entity.Width),new XAttribute("Height",entity.Height),new XAttribute("IsSelected",entity.IsSelected.ToString()),new XAttribute("CollectionName",entity.CollectionName),new XAttribute("GroupName",entity.GroupName),new XElement("Name",entity.Name),new XElement("IP",entity.IP),new XElement("X",entity.X),new XElement("Y",entity.Y)
                        );
this.xmlDoc.Add(carElement);
修改节点的值:
  element.SetElementValue("Name",entity.Name);
修改节点属性的值:

element.SetAttributeValue("Height",entity.Height);
保存:

this.xmlDoc.Save(filePath);


还有很多对元素节点的操作,这都不说了。具体参见

点击打开链接

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读