XML操作:2.LINQ TO XML(http://www.cnblogs.com/AlexLiu/archive/2008/10/27/linq.html)
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种方法。
- 其一是直接对Value和Name进行数值的修改。
- 使用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)的更多相关文章
- Linq to xml 操作带命名空间的xml
昨天需要操作用代码操作csproj文件,实现不同vs版本的切换. 在用XElement读取了csproj文件以后怎么也获取不到想要的对象. 反反复复试验了好多次都不得要领:先看下csproj文件的内容 ...
- 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 ...
- Linq to XML 读取XML 备忘笔记
本文转载:http://www.cnblogs.com/infozero/archive/2010/07/13/1776383.html Linq to XML 读取XML 备忘笔记 最近一个项目中有 ...
- linq to xml学习
http://www.cnblogs.com/greatverve/archive/2010/07/09/linq-to-xml-add-delete-update-query.html 记录一下,别 ...
- Linq学习<五> 运用linq查询Xml
这节将学习如何用 linq查询xml 一.我们先看看在xml中我们怎么操作 public void xmlWayToQueryXmlFile() { XmlDocument xmldoc = new ...
- XML格式示例 与 XML操作(读取)类封装
header('Content-Type: text/xml'); <?xml version="1.0" encoding="utf-8" standa ...
- Silverlight 使用IsolatedStorage新建XML文件,并且用LINQ查询XML
代码 Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-- ...
- LINQ系列:LINQ to XML操作
LINQ to XML操作XML文件的方法,如创建XML文件.添加新的元素到XML文件中.修改XML文件中的元素.删除XML文件中的元素等. 1. 创建XML文件 string xmlFilePath ...
- Linq对XML的简单操作
前两章介绍了关于Linq创建.解析SOAP格式的XML,在实际运用中,可能会对xml进行一些其它的操作,比如基础的增删该查,而操作对象首先需要获取对象,针对于DOM操作来说,Linq确实方便了不少,如 ...
随机推荐
- UVa 1647 (递推) Computer Transformation
题意: 有一个01串,每一步都会将所有的0变为10,将所有的1变为01,串最开始为1. 求第n步之后,00的个数 分析: 刚开始想的时候还是比较乱的,我还纠结了一下000中算是有1个00还是2个00 ...
- 永久的CheckBox(单选,全选/反选)!
<html> <head> <title>选择</title> <script type="text/javascript" ...
- 【C#学习笔记】smtp发邮件
using System; using System.Net; using System.Net.Mail; using System.Text; namespace ConsoleApplicati ...
- 【Unity3D】枪战游戏—弹孔设置
以子弹为原点,发射射线,如果射线检测到障碍物,则返回射线与障碍物的碰撞点 在该点处实例化出弹孔贴图 void Update () { transform.Translate (Vector3.forw ...
- 深入浅出ClassLoader
你真的了解ClassLoader吗? 这篇文章翻译自zeroturnaround.com的 Do You Really Get Classloaders? ,融入和补充了笔者的一些实践.经验和样例.本 ...
- Java泛型的好处
java 泛型是java SE 1.5的新特性,泛型的本质是参数化类型,也就是说所操作的数据类型被指定为一个参数.这种参数类型可以用在类.接口和方法的创建中,分别称为泛型类.泛型接口.泛型方法. ...
- ubuntu-12.04.1-desktop-x64下JDK环境的安装与配置
1.上oracle官网下载最新的JDK.在这里,我的系统是ubuntu-12.04.1-desktop-amd64,目前位置JDK的最新版本位7u9.jdk-for-linux有两种安装包,一种是rp ...
- cgroup隔离的知识点
tasks中写入的是线程号 cgroup.procs是进程号 ===================CPU隔离===================== 主机CPU核数: cat /proc/cpui ...
- ashx-auth-黑色简洁验证码
ylbtech-util: ashx-auth-黑色简洁验证码 ashx-auth-黑色简洁验证码 1.A,效果图返回顶部 1.B,源代码返回顶部 /ImageUniqueCode.ashx &l ...
- spring中的BeanFactory与ApplicationContext的作用和区别?
BeanFactory类关系继承图 1. BeanFactory类结构体系: BeanFactory接口及其子类定义了Spring IoC容器体系结构,由于BeanFactory体系非常的庞大和复杂, ...