LINQ to XML 建立,读取,增,删,改

 

LINQ to XML的出现使得我们再也不需要使用XMLDocument这样复杂的一个个的没有层次感的添加和删除。LINQ可以使的生成的XML文档在内存中错落有致。下面以一个小的例子说名LINQ to XML的简单应用。

  • 需要添加必要的引用。System.XML.Linq , System.XML.Xpath
  • 使用XDocument 建立一个XML文档。XDeclaration 声明开头字样。XComment 添加相应的注释。而XElement则是NODE的名字和内容。
  • 把一个XDocument 存储起来使用Save方法,而读取是Load,参数可以指定所要的路径。
  • 增加 使用Add()方法,新建节点。或者使用LINQ语句配合使用。
  • 读取,可以通过XElement对象的Descendant()的名字,读取相应的node,Value属性是node对应的值,而Name是node的名字。

var userName = from un in xe.Descendants("Name")
select un.Value;
  • 修改可以 使用2种方法。
  1. 其一是直接对Value和Name进行数值的修改。
  2. 使用Replace相关的方法等等。比如

var a = age.Single<XElement>(); 
a.ReplaceWith(new XElement("agettt", "26"));
//读取唯一一个,进行名字和数字的修改。
  • 删除一个或者多个node,或者单独删除里面的值而不删除节点名字。可以有多种方法,Remove ,Removeall,RemoveNodes等等方法。

下面是一个完整的控制台程序,以演示简单的增删改功能的实现。是不是比XMLDocument来的简单得多呢,大家赶快试试吧:)

Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml.Linq;
using System.Xml.XPath; namespace LINQTOXMLDEMO
{
class Program
{
staticvoid Main(string[] args)
{
XDocument userInfomation =new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment("This is a comment.Just input what you want to say."),
new XElement("UsersInfomation",
new XElement("User", new XAttribute("ID", "1"),
new XElement("Name", "Alex"),
new XElement("Hometown", "HRB"),
new XElement("Age", "22")),
new XElement("User",
new XAttribute("ID", "2"),
new XElement("Name", "Fu"),
new XElement("Hometown", "SY"),
new XElement("Age", "27")),
new XElement("User",new XAttribute("ID","3"),
new XElement("Name","Abe"),
new XElement("Hometown","HRB"),
new XElement("Age","24"))
)); // 显示所生成的XML在内存中的信息。并且按着所制定的路径保存。
Console.WriteLine(userInfomation);
userInfomation.Save(@"D:\1\userInfomation.xml"); XElement xd = XElement.Load(@"D:\1\userInfomation.xml");
GetAllUsername(xd);
Console.WriteLine();
GetAge(xd);
Console.WriteLine();
GetHometown(xd);
Console.WriteLine();
updateAge(xd);
//Console.WriteLine(xd);
deleteElement(xd);
Console.WriteLine();
addNode(xd);
Console.WriteLine(xd);
Console.ReadKey();
}
//得到所有name字段的名字
privatestaticvoid GetAllUsername(XElement xe)
{
var userName = from un in xe.Descendants("Name")
select un.Value;
foreach (var name in userName)
{
Console.WriteLine("name {0}" ,name);
}
}
//输出AGE是24的所有NODE
privatestaticvoid GetAge(XElement xe)
{
var age = from c in xe.Descendants("Age")
where c.Value =="24"
select c;
foreach (var a in age)
Console.WriteLine("AGE: {0}", a);
}
//移除所有的Name字段
privatestaticvoid deleteElement(XElement xe)
{
var user = from u in xe.Descendants("User")
select u;
foreach (var u in user)
{ var names = from name in u.Descendants("Name")
select name;
names.Remove();
}
}
//增加节点
privatestaticvoid addNode(XElement xe)
{
var user = from u in xe.Descendants("User")
select u;
foreach (var u in user)
{
u.Add(new XElement("Nation","China"));
}
}
//更新字段NODE的名字和内容。
privatestaticvoid updateAge(XElement xe)
{
var age = from c in xe.Descendants("Age")
where c.Value =="24"
select c;
var a = age.Single<XElement>();
a.ReplaceWith(new XElement("agettt", "26"));
}
//统计hometown为HRB的人数
privatestaticvoid GetHometown(XElement xe)
{
var hometown = from h in xe.Descendants("Hometown")
where h.Value =="HRB"
select h;
int count=0;
foreach (var h in hometown)
{
count++;
}
Console.WriteLine(count);
}
}
}

几个例子的作用,代码函数都有注释。比较简单。不需要太多的介绍。输出结果如下图所示。

XML操作:2.LINQ TO XML(http://www.cnblogs.com/AlexLiu/archive/2008/10/27/linq.html)的更多相关文章

  1. Linq to xml 操作带命名空间的xml

    昨天需要操作用代码操作csproj文件,实现不同vs版本的切换. 在用XElement读取了csproj文件以后怎么也获取不到想要的对象. 反反复复试验了好多次都不得要领:先看下csproj文件的内容 ...

  2. xml操作-Nested exception: org.xml.sax.SAXParseException: White spaces are required between publicId and systemId. 异常处理

    异常如下: org.dom4j.DocumentException: Error on line 2 of document file:///D:/workspaces/struts2/lesson0 ...

  3. Linq to XML 读取XML 备忘笔记

    本文转载:http://www.cnblogs.com/infozero/archive/2010/07/13/1776383.html Linq to XML 读取XML 备忘笔记 最近一个项目中有 ...

  4. linq to xml学习

    http://www.cnblogs.com/greatverve/archive/2010/07/09/linq-to-xml-add-delete-update-query.html 记录一下,别 ...

  5. Linq学习<五> 运用linq查询Xml

    这节将学习如何用 linq查询xml 一.我们先看看在xml中我们怎么操作 public void xmlWayToQueryXmlFile() { XmlDocument xmldoc = new ...

  6. XML格式示例 与 XML操作(读取)类封装

    header('Content-Type: text/xml'); <?xml version="1.0" encoding="utf-8" standa ...

  7. Silverlight 使用IsolatedStorage新建XML文件,并且用LINQ查询XML

    代码 Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-- ...

  8. LINQ系列:LINQ to XML操作

    LINQ to XML操作XML文件的方法,如创建XML文件.添加新的元素到XML文件中.修改XML文件中的元素.删除XML文件中的元素等. 1. 创建XML文件 string xmlFilePath ...

  9. Linq对XML的简单操作

    前两章介绍了关于Linq创建.解析SOAP格式的XML,在实际运用中,可能会对xml进行一些其它的操作,比如基础的增删该查,而操作对象首先需要获取对象,针对于DOM操作来说,Linq确实方便了不少,如 ...

随机推荐

  1. C#基本知识点-Readonly和Const的区别

    什么是静态常量(Const)和动态常量(Readonly)   先解释下什么是静态常量(Const)以及什么是动态常量(Readonly). 静态常量(Const)是指编译器在编译时候会对常量进行解析 ...

  2. 真正解决ASP.NET每一个页面首次访问超级慢的问题 (转载)

    原文:http://www.afuhao.com/article_articleId-219.shtml 摘要:ASP.NET页面首次打开很慢,但别的页面如果没有访问过,去访问也会慢.你也许认为它是在 ...

  3. javascript数组详解

    1.数组的一些方法: <script type="text/javascript"> //var arr = [1,2,3,4]; //性能略高 var arr = n ...

  4. Windows Live Writer测试插件

    这是用WLW写的,测试 这是图片: 这是地图: 这是代码: 一会重发

  5. LeetCode:Sort List

    Title: Sort a linked list in O(n log n) time using constant space complexity. 思路:考虑快速排序和归并排序,但是我的快速排 ...

  6. Shell中取时间格式方法

    Shell中取时间格式方法2007-09-13 15:35常用date的显示格式: date +%F //2007-03-06date +%Y%m%d//20070306 date +%T //23: ...

  7. 【转】VI/VIM常用命令

    原文网址:http://www.blogjava.net/woxingwosu/archive/2007/09/06/125193.html Vi是“Visual interface”的简称,它在Li ...

  8. WPF如何在同一个区域依次叠加显示多张图片呢?

    正如标题的问题,有时需要在已显示的图片的右上角(或其他区域)显示小图标,譬如下图的患者头像右上角显示病情图标:(这里不采用事先用PS编排成一个图片文件的方式,因为此方式普适性不好) 解决方案:绘制该复 ...

  9. POJ 2362 Square

    题意:给n个木棍,问能不能正好拼成一个正方形. 解法:POJ1011的简单版……不需要太多剪枝……随便剪一剪就好了……但是各种写屎来着QAQ 代码: #include<stdio.h> # ...

  10. 【剑指offer 面试题23】从上往下打印二叉树

    思路: 没啥好说的,BFS. C++: #include <iostream> #include <queue> using namespace std; struct Tre ...