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 =new XElement("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是一样的,这里不举例了