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. cocos2d-x 滚动文字(二)

    http://blog.csdn.net/kuovane/article/details/8131789 首先送上demo,下载地址为:demo下载地址 一,怎么在文字前面空两隔?只需在xml里的文字 ...

  2. 利用nginx+lua+memcache实现灰度发布

    一.灰度发布原理说明 灰度发布在百度百科中解释: 灰度发布是指在黑与白之间,能够平滑过渡的一种发布方式.AB test就是一种灰度发布方式,让一部分用户继续用A,一部分用户开始用B,如果用户对B没有什 ...

  3. Java [leetcode 4] Median of Two Sorted Arrays

    问题描述: There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of t ...

  4. RTP协议学习大总结从原理到代码

    from:http://wenku.baidu.com/view/aaad3d136edb6f1aff001fa5.html 一.流媒体概念 流媒体包含广义和狭义两种内涵:广义上的流媒体指的是使音频和 ...

  5. DirectShow建立一个视频捕捉程序

    DirectShow 提供了用应用程序从适当的硬件中捕捉和预览音/视频的能力.数据源包括:VCR,camera,TV tuner,microphone,或其他的数据源.一个应用程序可以立刻显示捕捉的数 ...

  6. poj 3694 Network

    题意: 添加每条新连接后网络中桥的数目// 超时 先放着了 ,下次改//早上这代码超时了 下午改了,代码在下面#include <iostream> #include <algori ...

  7. IE8按F12不显示开发人员工具窗口

    转:http://www.cnblogs.com/micromouse/archive/2010/07/11/1775174.html 网上搜来的,记录一下,免得以后忘了 F12将开发人员工具启动后, ...

  8. Delphi RICHEDIT中插入图象

    unit InsRich;interfaceuses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms ...

  9. codeforces 682D Alyona and Strings

    #include <cstdio> #include <iostream> #include <ctime> #include <vector> #in ...

  10. ARM指令协处理器处理指令

    ARM支持16个协处理器,在程序执行过程中,每个协处理器忽略属于ARM处理器和其他协处理器指令,当一个协处理器硬件不能执行属于她的协处理器指令时,就会产生一个未定义的异常中断,在异常中断处理程序中,可 ...