C # to XML operations: A class that processes XML files (1)

Source: Internet
Author: User
Tags httpcontext log log
C # Operations XML preliminary (7)
The fourth chapter: General XML Processing method (1)
Since we can use a dataset to manipulate an XML file, that's really convenient, and he's perfectly capable of using an XML file as a table.
So we can work with one of these C # classes to manipulate XML and do database-like operations: using System; Using System.Text; Using System.IO; Using System.Xml; Using System.Data; namespace XmlBook.Com.Sem.Tools {///<summary>///copyrights: Copyright by Sem IT Department///version: 0.0.1///file: Xmlbook . Com.Sem.Tools.XmlDataBase.cs///Purpose: To provide some ways to treat XML as a database///author: Ouyang Yun @2005-04-09///mailbox: outrace@soueast-motor.com///Modify: </summary> public class XMLdatabase {#region Private membership private string strdatafile = null;///<summary>///number According to the set///</summary> private DataSet myds = null; <summary>///character filter array such as "id= ' 1 ' and username= ' trace '"///</summary> private string strfilter = null; <summary>///sorted fields such as "ID desc,username"///</summary> private string strsort = null; <summary>///the set of field names in the data collection///</summary> private string[] strfields = null; <summary>///data Array in data collection///</summary> private string[] strdata = null; <summary>///template file full path///</summary>private string strtemplatefile = null; #endregion #region Common Properties///<summary>///template file path///</summary> public string Strtemplatefile {Set{this.strte Mplatefile = value;} Get{return This.strtemplatefile}} <summary>///Data File path///</summary> public string Strdatafile {set{this.strdatafile = value;} get{return This.strdatafile;} ///<summary>///character filter array///</summary> public string strfilter {set{this.strfilter = value;}///<sum Mary>///sorted fields///</summary> public string StrSort {set{this.strsort = value;}///<summary>///data collection The field name///</summary> public string[] Strfields {set{this.strfields = value;}}///<summary>///data array in the data collection// /</summary> public string[] Strdata {set{this.strdata = value}}///<summary>///data collection, which can be placed in cache for invocation///</ Summary> public DataSet myds {set{this.myds = value;} Get{return this.myds.}} #endregion public XMLdatabase () {/// TODO: Provide some methods to treat XML as a database//}<summary>///Get the contents of the XML file and fill in the dataset///</summary> private void Open () {try {this.myds = new DataSet (); F Ilestream fin; Fin = new FileStream (This.strdatafile, FileMode.Open, FileAccess.Read, fileshare.readwrite); THIS.MYDS.READXML (Fin); Fin. Close (); catch (Exception ee) {log log = new log (); log. struser = "System"; Log. Strdepartment = "Read XML data"; Log. strFileName = "Com.Sem.Tools.XmlDataBase"; Log. strdescription = ee. message; Log. Writelog (); }///<summary>///writes the results of the operation to XML///</summary> private void Save () {try {this.myDs.WriteXml (this.strdatafil E, Xmlwritemode.writeschema); catch (Exception ee) {log log = new log (); log. struser = "System"; Log. Strdepartment = "Save XML data"; Log. strFileName = "Com.Sem.Tools.XmlDataBase"; Log. strdescription = ee. message; Log. Writelog (); }///<summary>///get specific Data Views///generally in data binding, we can easily generate a view for binding///</summary>///<returns> Data View </re Turns> public DataView Selectview () {if (this.myds = = null) this. Open (); DataView MYDV = new DataView (this.myds.tables[0]); if (strfilter!= null) Mydv.rowfilter = This.strfilter; Mydv.sort = This.strsort; return MYDV; ///<summary>///Get a specific row///use the row because sometimes we just need one or more lines of records///for example, when we judge a login, we just need the line of an ID, and then match its password entry///</ Summary>///<returns> Each row data </returns> public datarow[] Selectrows () {if (this.myds = null) this. Open (); datarow[] myrows = myds.tables[0]. Select (This.strfilter); return myrows; ///<summary>///Inserts a data into the XML///</summary>///<returns> operation succeeded </returns> public bool Insert ( {if (this.myds = null) this. Open (); try {DataRow NewRow = myds.tables[0]. NewRow (); for (int i = 0; i < this.strFields.Length i++) {newrow[this.strfields[i]] = This.strdata[i];} Myds.tables[0]. Rows.Add (NewRow); This. Save (); return true; catch (Exception ee) {log log = new log (); log. struser = "System"; Log. Strdepartment = "Write XML data"; Log. strFileName = "Com.Sem.Tools.XmlDataBase"; Log. strdescription = ee. message; Log. Writelog (); return false; }///<summary>///update data, this time to ensure that Strfields and strdata two array of dimensions consistent///</summary>///<returns> Whether the update succeeded &LT;/R Eturns> public bool Update () {if (this.myds = null) this. Open (); try {datarow[] Editrow = myds.tables[0]. Select (This.strfilter); for (int j=0; j< editrow.length; j) {for (int i = 0; i < this.strFields.Length; i++) {editrow[j][this.strfields[i ] = This.strdata[i]; }} this. Save (); return true; catch (Exception ee) {log log = new log (); log. struser = "System"; Log. strdepartment = "Update xml data"; Log. strFileName = "Com.Sem.Tools.XmlDataBase"; Log. strdescription = ee. message; Log. Writelog (); return false; }///<summary>///delete data///</summary>///<returns> Delete success </returns> public bool Delete () {if ( This.myds = = null) this. Open (); try {datarow[] Editrow = myds.tables[0]. Select (This.strfilter); for (int i=0;i<editrow.length;i++) {editrow[i]. Delete (); } this. Save (); return true; catch (Exception ee) {Log log = new Log (); Log. struser = "System"; Log. strdepartment = "Delete xml data"; Log. strFileName = "Com.Sem.Tools.XmlDataBase"; Log. strdescription = ee. message; Log. Writelog (); return false; }///<summary>///According to a template, create a new XML file (provided that you must have a template file and determine the destination file path)///</summary>///<returns> Write Success < /returns> public bool Create () {try {XmlDocument doc = new XmlDocument (); XmlTextReader reader = new XmlTextReader (This.strtemplatefile); Doc. Load (reader); XmlElement member; XmlNode root = Doc. DocumentElement; for (int i = 0; i < This.strFields.Length, i++) {member = doc. CreateElement (Strfields[i]. ToString ()); Member. innertext = This.strdata[i]. ToString (); Root. AppendChild (member); } XmlTextWriter XmlWriter = new XmlTextWriter (this.strdatafile,null); xmlwriter.formatting = formatting.indented; Doc. Save (XmlWriter); Xmlwriter.close (); Reader. Close (); return true; catch (Exception ee) {log log = new log (); log. struser = "System"; Log. Strdepartment = "New XML data"; Log. strFileName = "Com.Sem.ToolS.xmldatabase "; Log. strdescription = ee. message; Log. Writelog (); return false; }///<summary>///free resources///</summary> public void Clear () {if (this.myds!= null) {this.myDs.Dispose (); } } } }
Class that introduces another log handler, which is sent here
Using System; Using System.Xml; Using System.Web; namespace XmlBook.Com.Sem.Tools {///<summary>///copyrights: Copyright by Sem IT Department///version: 0.0.1///file: Xmlbook . Com.Sem.Tools.Log.cs///Purpose: To provide a method of writing Log (that is, to write an error to an XML record)///Author: Owaning @2005-04-09///mailbox: outrace@soueast-motor.com///Modify: </summary> public class Log {#region Private member HttpContext objcontext = httpcontext.current;///<summar y>///log file path///</summary> private string logFile = null; <summary>///operator///</summary> private string struser = null; <summary>///belongs to///</summary> private string strdepartment = null; <summary>///is manipulating the filename///</summary> private string strfilename = null; <summary>///operation time///</summary> private string strtime = null; <summary>///Error description///</summary> private string strdescription = null; #endregion #region Common Properties///<summary>///operator///</summary> public stringstruser {Get{return This.struser} set{this.struser = value;}///<summary>///the filename being manipulated///</summary> pub Lic string strFileName {Get{return this.strfilename; set{this.strfilename = value;}///<summary>///belongs to Lt;/summary> public string Strdepartment {Get{return this.strdepartment} set{this. strdepartment = value;}///< Summary>///operation time///</summary> public string Strtime {Get{return this.strtime;} set{this.strtime = value;}}/ <summary>///Error description///</summary> public string strdescription {Get{return this.strdescription;} set{this. Strdescription = value;} #endregion public log () {///TODO: Provides a way to write log (that is, write the error to the XML record)//}///<summary>///writes the content to the log file///</summar y> public void Writelog () {this.logfile = This.objContext.Server.MapPath ("./log/log.config"); try {xmldocument doc = New XmlDocument (); Doc. Load (This.logfile); XmlElement newlog = doc. CreateElement ("Log"); XmlElement newuser = doc. CreateeLement ("User"); Newuser.innertext = This.struser; Newlog.appendchild (NewUser); XmlElement newdepartment = doc. CreateElement ("Department"); Newdepartment.innertext = this.strdepartment; Newlog.appendchild (newdepartment); XmlElement newfilename = doc. CreateElement ("FileName"); Newfilename.innertext = this. strFileName; Newlog.appendchild (NewFileName); XmlElement newtime = doc. CreateElement ("Time"); Newtime.innertext = DateTime.Now.ToString (); Newlog.appendchild (NewTime); XmlElement newdescription = doc. CreateElement ("Description"); Newdescription.innertext = this.strdescription; Newlog.appendchild (newdescription); Doc. Documentelement.appendchild (Newlog); Doc. Save (This.logfile); The catch (Exception ex) {httpcontext objcontext = httpcontext.current; ObjContext.Response.Write (ex. message); } finally {}}}
so that we can easily take an XML file as a table to manipulate the use of the example, I will give the next article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.