加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Linq to XML 增删改查

发布时间:2020-12-16 05:51:48 所属栏目:百科 来源:网络整理
导读:?? Linq to XML 增删改查 2011-10-09 21:12:35 |分类: .Net(C#) |标签: linqxmlxdocumentxelement | 举报 | 字号 大 中 小 订阅 Linq to XML同样是对原C#访问XML文件的方法的封装,简化了用xpath进行xml的查询以及增加,修改,删除xml元素的操作。 C#访问X
??

Linq to XML 增删改查

2011-10-09 21:12:35|分类:.Net(C#)|标签:linqxmlxdocumentxelement|举报|字号订阅

Linq to XML同样是对原C#访问XML文件的方法的封装,简化了用xpath进行xml的查询以及增加,修改,删除xml元素的操作。

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>

publicbool Add()

{

XElement db =new XElement("DataBase",

newXAttribute("id",ID),

newXElement("company",newXAttribute("value",Company)),

newXElement("server",Server)),

newXElement("database",DataBase)),

newXElement("username",UserName)),

newXElement("password",Password))

);

try

{

//XElementAdd方法

//XElement doc = XElement.Load(filePath);

//doc.Add(db);

//XDocumentAdd方法

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()

简单举个例就知道了

[c-sharp] view plain copy print ?
  1. //wewillusethistostoreareferencetooneoftheelementsintheXMLtree.
  2. XElementfirstParticipant;
  3. XDocumentxDocument=newXDocument(
  4. newXElement("BookParticipants",firstParticipant=
  5. newXElement("BookParticipant",
  6. newXAttribute("type","Author"),
  7. newXElement("FirstName","Joe"),
  8. newXElement("LastName","Rattz"))));
  9. Console.WriteLine(firstParticipant.Attribute("type").Value);

[c-sharp] view plain copy print ?
  1. //wewillusethistostoreareferencetooneoftheelementsintheXMLtree.
  2. XElementfirstParticipant;
  3. XDocumentxDocument=newXDocument(
  4. newXElement("BookParticipants",
  5. newXAttribute("experience","first-time"),
  6. newXElement("FirstName",
  7. newXElement("LastName","Rattz"))));
  8. foreach(XAttributeattrinfirstParticipant.Attributes())
  9. {
  10. Console.WriteLine(attr);
  11. }

输出

type="Author"

experience="first-time"

那么往元素上加属性有如下方法

XElement.Add()

XElement.AddFirst()

XElement.AddBeforeThis()

XElement.AddAfterThis()

删除元素属性有如下方法

XAttribute.Remove()

更新元素属性是这样的

XElement.Attribute("someattribute").Value = "beginner"

同样的属性也有XElement.SetAttributeValue() 方法

用起来和XElement.SetElementValue是一样的,这里不举例了

??
??

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读