Linq To XML 简单操作

时间:2014-04-30 03:03:33   收藏:0   阅读:363

 

加载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","清华大学出版社"));

 

给元素添加命名空间

mamicode.com,码迷
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", "清华大学出版社"));
mamicode.com,码迷

 

添加注释

mamicode.com,码迷
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", "清华大学出版社"));
mamicode.com,码迷

 

添加节点的属性

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", "清华大学出版社"));

 


向原有的文档添加节点

mamicode.com,码迷
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"));
mamicode.com,码迷

 


查询

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

 

Linq To XML 简单操作,码迷,mamicode.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!