Linq to XML additions and deletions
2011-10-09 21:12:35| Category:. Net (C #) | Tags: LINQ xml XDocument xelement | report | font size large small and Medium subscription LINQ to XML is also an encapsulation of methods that access XML files from the original C #, simplifying the operation of XML queries with XPath and additions, modifications, and deletions of XML elements.
Common classes for C # access to XML files: Xmldocument,xmlelement,xmlattribute,xmlnode,xmltext, etc.;
common classes in Linq to XML: Xdocument,xelement,xattribute.
Nonsense not much to say, directly on the code:
The XML file data format is as follows
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>
Increase
</summary>
<returns></returns>
public bool Add ()
{
XElement db =new XElement ("DataBase",
Newxattribute ("id", id),
Newxelement ("Company", Newxattribute ("value"),
Newxelement ("Server", Newxattribute ("value", server)),
Newxelement ("Database", Newxattribute ("value", database)),
Newxelement ("username", Newxattribute ("value", username)),
Newxelement ("Password", Newxattribute ("value", password))
);
Try
{
Using the XElement Add method
XElement doc = Xelement.load (FilePath);
Doc. ADD (DB);
Using the XDocument Add method
Doc. Element ("DataBases"). ADD (DB);
Doc. Save (FilePath);
Returntrue;
}
Catch
{
Returnfalse;
}
}
<summary>
By deleting
</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>
Change
</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);