Linq To XML 简单操作

 

加载xml文件和保存xml文件

XDocument doc = XDocument.Load(Server.MapPath("\\xmlfile\\Book.xml"));

doc.Save(Server.MapPath("\\xmlfile\\BookBackup.xml"));

 

创建元素

XElement xe = new XElement("book",new XElement("bookname","asp.net mvc 4 高级编程"),
new XElement("bookAuthor","Jon Galloway"),
new XElement("publisher","清华大学出版社"));

 

给元素添加命名空间

XNamespace ns = "http://mvctest/root"; //用来给根节点添加命名空间
XNamespace ns1 = "http://mvctest/sub"; //用来给子元素添加命名空间
XElement xe = new XElement(ns+"book", new XElement(ns1+"bookname", "asp.net mvc 4 高级编程"),
new XElement(ns1+"bookAuthor", "Jon Galloway"),
new XElement(ns1+"publisher", "清华大学出版社"));

 

添加注释

XComment comment = new XComment("这里是注释");
doc.Add(comment);
XElement xe = new XElement("book", new XElement("bookname", "asp.net mvc 4 高级编程"),
new XComment("下面是书的作者和出版社"),
new XElement("bookAuthor", "Jon Galloway"),
new XElement("publisher", "清华大学出版社"));

 

添加节点的属性

XElement xe = new XElement("book",new XAttribute("isbn","123456789"),
new XElement("bookname", "asp.net mvc 4 高级编程"),
new XComment("下面是书的作者和出版社"),
new XElement("bookAuthor", "Jon Galloway"),
new XElement("publisher", "清华大学出版社"));

 


向原有的文档添加节点

XDocument doc = XDocument.Load(Server.MapPath("\\xmlfile\\Book.xml"));
XElement xe = new XElement("book",new XElement("bookname", "asp.net mvc 4 高级编程"),
new XElement("bookAuthor", "Jon Galloway"),
new XElement("publisher", "清华大学出版社"));
doc.Root.Add(xe);
doc.Save(Server.MapPath("\\xmlfile\\Book.xml"));

 


查询

XDocument doc = XDocument.Load(Server.MapPath("\\xmlfile\\Book.xml"));
var result = from book in doc.Descendants("bookname")
                   where book.ToString().Contains("基础")
                   select book.Value;
           

 

转载于:https://www.cnblogs.com/ixincheng/p/3695829.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值