Linq to XML 增删改查
来源:互联网 发布:mac 环境变量 编辑:程序博客网 时间:2024/05/17 03:14
Linq to XML 增删改查
2011-10-09 21:12:35| 分类:.Net(C#)| 标签:linq xml xdocument xelement |举报|字号大中小 订阅
C#访问XML文件的常用类:XmlDocument,XmlElement,XmlAttribute,XmlNode,XmlText等;
Linq to XML 中的常用类 :XDocument,XElement,XAttribute。
废话不多说了,直接上代码:
xml文件数据格式如下
publicclassDataBaseInfo
{
publicstring ID {get;set; }
publicstring Company {get;set; }
publicstring Server {get;set; }
publicstring DataBase {get;set; }
publicstring UserName {get;set; }
publicstring Password {get;set; }
privatestaticXDocument doc =new XDocument();
publicstaticstring filePath =".\\DataBaseInfo.xml";
public DataBaseInfo() {
doc =XDocument.Load(filePath);
}
public DataBaseInfo(string filepath):this()
{
filePath = filepath;
}
///<summary>
///增
///</summary>
///<returns></returns>
public bool Add()
{
XElement db =newXElement("DataBase",
newXAttribute("id", ID),
newXElement("company",newXAttribute("value",Company)),
newXElement("server",newXAttribute("value",Server)),
newXElement("database",newXAttribute("value",DataBase)),
newXElement("username",newXAttribute("value",UserName)),
newXElement("password",newXAttribute("value", Password))
);
try
{
//用XElement的Add方法
//XElement doc = XElement.Load(filePath);
//doc.Add(db);
//用XDocument的Add方法
doc.Element("DataBases").Add(db);
doc.Save(filePath);
returntrue;
}
catch
{
returnfalse;
}
}
///<summary>
///删
///</summary>
///<param name="id"></param>
///<returns></returns>
publicstaticbool Remove(string id)
{
XElement xe = (from dbin doc.Element("DataBases").Elements("DataBase")where db.Attribute("id").Value == idselect db).Single() asXElement;
try
{
xe.Remove();
doc.Save(filePath);
returntrue;
}
catch
{
returnfalse;
}
}
///<summary>
///改
///</summary>
///<returns></returns>
publicbool Modify()
{
XElement xe = (from dbin doc.Element("DataBases").Elements("DataBase")where db.Attribute("id").Value.ToString() == IDselect db).Single();
try
{
xe.Element("company").Attribute("value").Value = Company;
xe.Element("server").Attribute("value").Value = Server;
xe.Element("database").Attribute("value").Value = DataBase;
xe.Element("username").Attribute("value").Value = UserName;
xe.Element("password").Attribute("value").Value = Password;
doc.Save(filePath);
returntrue;
}
catch
{
returnfalse;
}
}
///<summary>
///查
///</summary>
///<returns></returns>
publicList<DataBaseInfo> GetAll()
{
List<DataBaseInfo> dbs = (from dbin doc.Element("DataBases").Elements("DataBase")
selectnewDataBaseInfo
{
ID = db.Attribute("id").Value.ToString(),
Company = db.Element("company").Attribute("value").Value.ToString(),
Server = db.Element("server").Attribute("value").Value.ToString(),
DataBase = db.Element("database").Attribute("value").Value.ToString(),
UserName = db.Element("username").Attribute("value").Value.ToString(),
Password = db.Element("password").Attribute("value").Value.ToString()
}).ToList();
return dbs;
}
怎么样,如何对之前DOM方式访问XML熟悉的话, 是不是发现简单了不少呢?xml文件如下:<?xml version="1.0" encoding="UTF-8"?>
<record_info RecordIndex="1" Upload2ShareCenterTimes="1" Upload2ResShareCenter="1" Upload2ShareCenterStatus="2">
<LessonGUID>22DE52E8-3AB6-42DE-9014-2E44B33A0E11</LessonGUID>
<RecTime StartTime="2011-06-15 14:49:36" EndTime="2011-06-15 14:49:51"/>
<CourseName>22</CourseName>
<LessonName>11</LessonName>
<SpeakerName>22</SpeakerName>
<Introduction/>
<ImageIndex>
<Index Name="24008984.jpg" Time="00:00:00"/>
</ImageIndex>
<ChannelInfo Count="4">
<Channel Name="教师桌面" Type="0" ID="0" Resolution="640 480" Quality="60" BandWidth="768" FrameRate="15" Keyframe="100" EncMode="VBR" Deinterlace="0" Denoise="0"/>
<Channel Name="老师通道" Type="1" ID="1" Resolution="640 480" Quality="60" BandWidth="768" FrameRate="25" Keyframe="100" EncMode="CBR" Deinterlace="1" Denoise="1"/>
<Channel Name="学生通道" Type="3" ID="3" Resolution="640 480" Quality="60" BandWidth="768" FrameRate="25" Keyframe="100" EncMode="VBR" Deinterlace="1" Denoise="1"/>
<Channel Name="全景视频" Type="2" ID="2" Resolution="720 576" Quality="60" BandWidth="768" FrameRate="25" Keyframe="100" EncMode="VBR" Deinterlace="1" Denoise="1"/>
</ChannelInfo>
<VidInfo IsRecSM="1" IsRecMM="1" SMFormat="1" MMFormat="2" TotalTime="00:00:12">
<Vid_SM SplitCount="4">
<RecFile Name="20110615144936.iac" Format="1" Channel="-1"/>
</Vid_SM>
<Vid_MM VidSize="720 576">
<RecFile Name="20110615144936_M.wmv" Format="2"/>
</Vid_MM>
</VidInfo>
</record_info>
要求读取<RecFile Name="20110615144936_M.wmv" Format="2"/>该节点中的Name,并要求Format=2
实现代码如下:
public static string GetVideoFile(string url)
{
string videoFilename = null;
//var ss = from e in XDocument.Load(url).Elements("record_info").Elements("Vid_MM").Elements("RecFile")
var query = from c in XDocument.Load(url).Elements("record_info").Elements("VidInfo").Elements("Vid_MM").Elements("RecFile")
where (string)c.Attribute("Format").Value == "2"
select c;
foreach (var book in query)
{
videoFilename=book.Attribute("Name").Value;
}
return videoFilename==null?null:videoFilename;
}
获取元素属性有两个方法,XElement.Attribute() 和XElement.Attributes()
简单举个例就知道了
- // we will use this to store a reference to one of the elements in the XML tree.
- XElement firstParticipant;
- XDocument xDocument = new XDocument(
- new XElement("BookParticipants", firstParticipant =
- new XElement("BookParticipant",
- new XAttribute("type", "Author"),
- new XElement("FirstName", "Joe"),
- new XElement("LastName", "Rattz"))));
- Console.WriteLine(firstParticipant.Attribute("type").Value);
- // we will use this to store a reference to one of the elements in the XML tree.
- XElement firstParticipant;
- XDocument xDocument = new XDocument(
- new XElement("BookParticipants", firstParticipant =
- new XElement("BookParticipant",
- new XAttribute("type", "Author"),
- new XAttribute("experience", "first-time"),
- new XElement("FirstName", "Joe"),
- new XElement("LastName", "Rattz"))));
- foreach(XAttribute attr in firstParticipant.Attributes())
- {
- Console.WriteLine(attr);
- }
输出
type="Author"
experience="first-time"
那么往元素上加属性有如下方法
XElement.Add()
XElement.AddFirst()
XElement.AddBeforeThis()
XElement.AddAfterThis()
删除元素属性有如下方法
XAttribute.Remove()
更新元素属性是这样的
XElement.Attribute("someattribute").Value = "beginner"
同样的属性也有XElement.SetAttributeValue() 方法
用起来和XElement.SetElementValue是一样的,这里不举例了
- Linq to XML 增删改查
- Linq to Xml 增删查改
- Linq to XML 增删改查
- Linq to XML 增删改查
- Linq to XML增删改查
- Linq to XML 增删改查
- LINQ to XML实现XML文档的增删改查
- Linq To Xml操作XML增删改查
- Linq to xml实现xml数据增删改查
- Linq技术二:Linq to XML及xml增删改查的不同实现方式
- linq for xml增删查改
- ORM, Linq to sql增删改查
- Linq to sql增删改查
- LinQ To Entity的增删改查
- LinQ To Entity的增删改查
- LinQ To Entity的增删改查
- LinQ To Entity的增删改查
- LINQ to SQL之增删改查
- Linux shell脚本的字符串截取
- [iOS] NSInvocation简单使用
- 抽象类与接口
- 【大数问题】 HDOJ 1316 How Many Fibs?
- 【BZOJ】【P1038】【ZJOI2008】【瞭望塔】【题解】【二分+模拟退火】
- Linq to XML 增删改查
- 手机游戏软件大爆炸时代
- 认识hasLayout——IE浏览器css bug的一大罪恶根源
- C语言实现链表的相关操作
- Codeforces Round #264 (Div. 2)
- Cocos2dx引擎优化 自定义资源包系统
- memset函数实现
- 多线程编程4------面试题使用资源互斥类AtomicInteger
- 在自遮挡下的单目图像3D姿态估计 Monocular Image 3D Human Pose Estimation under Self-Occlusion (ICCV 13)