Linq to XML 增删改查

来源:互联网 发布:mac 环境变量 编辑:程序博客网 时间:2024/05/17 03:14


Linq to XML 增删改查  

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

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>

           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

               {

                   //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 plaincopyprint?
  1. //  we will use this to store a reference to one of the elements in the XML tree.   
  2. XElement firstParticipant;   
  3.    
  4. XDocument xDocument = new XDocument(   
  5.   new XElement("BookParticipants", firstParticipant =   
  6.     new XElement("BookParticipant",    
  7.       new XAttribute("type""Author"),   
  8.       new XElement("FirstName""Joe"),   
  9.       new XElement("LastName""Rattz"))));   
  10.    
  11. Console.WriteLine(firstParticipant.Attribute("type").Value);   

 

 

[c-sharp] view plaincopyprint?
  1. //  we will use this to store a reference to one of the elements in the XML tree.   
  2. XElement firstParticipant;   
  3.    
  4. XDocument xDocument = new XDocument(   
  5.   new XElement("BookParticipants", firstParticipant =   
  6.     new XElement("BookParticipant",    
  7.       new XAttribute("type""Author"),   
  8.       new XAttribute("experience""first-time"),   
  9.       new XElement("FirstName""Joe"),   
  10.       new XElement("LastName""Rattz"))));   
  11.    
  12. foreach(XAttribute attr in firstParticipant.Attributes())   
  13. {   
  14.     Console.WriteLine(attr);   
  15. }   

 

 

输出

 

type="Author" 

experience="first-time" 

 

 

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

 

XElement.Add() 

XElement.AddFirst() 

XElement.AddBeforeThis() 

XElement.AddAfterThis() 

 

删除元素属性有如下方法

XAttribute.Remove() 

 

更新元素属性是这样的

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

 

 

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

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



0 0
原创粉丝点击