C#之XML文件操作
一 XMLHelper
usingSystem;usingSystem.Globalization;usingSystem.IO;usingSystem.IO.Compression;usingSystem.Runtime.Serialization.Formatters.Binary;usingSystem.Text;usingSystem.Xml;usingSystem.Xml.Serialization;namespaceHelper{publicclassXMLHelper{publicstaticXmlNodeCreate(stringnodeName){vardoc=newXmlDocument();XmlNodenode=doc.CreateElement(nodeName);returnnode;}publicstaticXmlAttributeCreateAttribute(XmlNodenode,stringattributeName,stringvalue){try{XmlDocumentdoc=node.OwnerDocument;XmlAttributeattr=doc.CreateAttribute(attributeName);attr.Value=value;node.Attributes.SetNamedItem(attr);returnattr;}catch(Exceptionerr){stringdesc=err.Message;returnnull;}}publicstaticXmlNodeObjectToXML(objectconfig){varxnd=newXmlDocument();if(config!=null){//we need the type to serializeTypet=config.GetType();varser=newXmlSerializer(t);//will hold the xmlusing(varwriter=newStringWriter(CultureInfo.InvariantCulture)){ser.Serialize(writer,config);xnd.LoadXml(writer.ToString());writer.Close();}}returnxnd.DocumentElement;}publicstaticobjectXMLToObject(XmlNodenode,TypeobjectType){objectconvertedObject=null;if(node!=null){using(varreader=newStringReader(node.OuterXml)){varser=newXmlSerializer(objectType);convertedObject=ser.Deserialize(reader);reader.Close();}}returnconvertedObject;}}publicclassXmlSerializerHelper{/// <summary>/// 读取XML文件/// </summary>/// <param name="XmlFilePath"></param>/// <param name="type"></param>/// <returns></returns>publicstaticobjectReadXML(stringXmlFilePath,Typetype){if(!File.Exists(XmlFilePath)){thrownewException($"File{XmlFilePath}not Exists");}using(varfs=newFileStream(XmlFilePath,FileMode.Open)){returnnewXmlSerializer(type).Deserialize(fs);}}/// <summary>/// 序列化XML文件/// </summary>/// <param name="data"></param>/// <param name="file"></param>/// <param name="type"></param>/// <returns></returns>publicstaticboolWriteXML(objectdata,stringfile,Typetype){using(varfs=newFileStream(file,FileMode.Create)){newXmlSerializer(type).Serialize(fs,data);}returntrue;}publicstaticstringXMLSerialize<T>(Tentity){varbuffer=newStringBuilder();varserializer=newXmlSerializer(typeof(T));using(TextWriterwriter=newStringWriter(buffer)){serializer.Serialize(writer,entity);}returnbuffer.ToString();}publicstaticstringByteToString(byte[]data){returnEncoding.Default.GetString(data);}publicstaticbyte[]StringToByte(stringvalue){returnEncoding.Default.GetBytes(value);}publicstaticTDeXMLSerialize<T>(stringxmlString){TcloneObject=default(T);varbuffer=newStringBuilder();buffer.Append(xmlString);varserializer=newXmlSerializer(typeof(T));using(TextReaderreader=newStringReader(buffer.ToString())){Objectobj=serializer.Deserialize(reader);cloneObject=(T)obj;}returncloneObject;}/// <summary>/// 把对象序列化为字符串/// </summary>/// <param name="pObj"></param>/// <returns></returns>publicstaticbyte[]SerializeObject(objectpObj){if(pObj==null)returnnull;var_memory=newMemoryStream();varformatter=newBinaryFormatter();formatter.Serialize(_memory,pObj);_memory.Position=0;varread=newbyte[_memory.Length];_memory.Read(read,0,read.Length);_memory.Close();returnCompress(read);}/// <summary>/// 把字节反序列化成相应的对象/// </summary>/// <param name="pBytes">字节流</param>/// <returns>object</returns>publicstaticobjectDeserializeObject(byte[]pBytes){object_newOjb=null;if(pBytes==null)return_newOjb;var_memory=newMemoryStream(Decompress(pBytes));_memory.Position=0;varformatter=newBinaryFormatter();_newOjb=formatter.Deserialize(_memory);_memory.Close();return_newOjb;}/// <summary>/// Write byte[] to file/// </summary>publicstaticvoidWriteByteToFile(byte[]dataSource,stringfilePath){varfs=newFileStream(filePath,FileMode.Create);//将byte数组写入文件中fs.Write(dataSource,0,dataSource.Length);fs.Close();}/// <summary>/// Read byte from file/// </summary>/// <param name="filePath"></param>/// <returns></returns>publicstaticbyte[]ReadByteFromFile(stringfilePath){varfs=newFileStream(filePath,FileMode.Open);//获取文件大小longsize=fs.Length;vararray=newbyte[size];//将文件读到byte数组中fs.Read(array,0,array.Length);fs.Close();returnarray;}/// <summary>/// Write object to file/// </summary>publicstaticvoidWriteObjectToFile(objectdataSource,stringfilePath){varfs=newFileStream(filePath,FileMode.Create);byte[]arraysource=SerializeObject(dataSource);//将byte数组写入文件中fs.Write(arraysource,0,arraysource.Length);fs.Close();}/// <summary>/// Read object from file/// </summary>/// <param name="filePath"></param>/// <returns></returns>publicstaticobjectReadObjectFromFile(stringfilePath){varfs=newFileStream(filePath,FileMode.Open);//获取文件大小longsize=fs.Length;vararray=newbyte[size];//将文件读到byte数组中fs.Read(array,0,array.Length);fs.Close();returnDeserializeObject(array);}/// <summary>/// 字符串压缩/// </summary>/// <param name="strSource"></param>/// <returns></returns>publicstaticbyte[]Compress(byte[]data){try{varms=newMemoryStream();varzip=newGZipStream(ms,CompressionMode.Compress,true);zip.Write(data,0,data.Length);zip.Close();varbuffer=newbyte[ms.Length];ms.Position=0;ms.Read(buffer,0,buffer.Length);ms.Close();returnbuffer;}catch(Exceptione){thrownewException(e.Message);}}/// <summary>/// 字符串解压缩/// </summary>/// <param name="strSource"></param>/// <returns></returns>publicstaticbyte[]Decompress(byte[]data){try{varms=newMemoryStream(data);varzip=newGZipStream(ms,CompressionMode.Decompress,true);varmsreader=newMemoryStream();varbuffer=newbyte[0x1000];while(true){intreader=zip.Read(buffer,0,buffer.Length);if(reader<=0){break;}msreader.Write(buffer,0,reader);}zip.Close();ms.Close();msreader.Position=0;buffer=msreader.ToArray();msreader.Close();returnbuffer;}catch(Exceptione){thrownewException(e.Message);}}/// <summary>/// string 压缩/// </summary>/// <param name="str"></param>/// <returns></returns>publicstaticstringCompressString(stringstr){stringcompressString="";byte[]compressBeforeByte=Encoding.GetEncoding("UTF-8").GetBytes(str);byte[]compressAfterByte=Compress(compressBeforeByte);//compressString = Encoding.GetEncoding("UTF-8").GetString(compressAfterByte);compressString=Convert.ToBase64String(compressAfterByte);returncompressString;}/// <summary>/// string 解压缩/// </summary>/// <param name="str"></param>/// <returns></returns>publicstaticstringDecompressString(stringstr){stringcompressString="";//byte[] compressBeforeByte = Encoding.GetEncoding("UTF-8").GetBytes(str);byte[]compressBeforeByte=Convert.FromBase64String(str);byte[]compressAfterByte=Decompress(compressBeforeByte);compressString=Encoding.GetEncoding("UTF-8").GetString(compressAfterByte);returncompressString;}}}
二 DataModel
publicclassDataModel{[Category("算法参数"),Description("面积阈值")]publicdoubleArea{get;set;}=100;[Category("算法参数"),Description("宽阈值")]publicdoubleWidth{get;set;}=200;[Category("算法参数"),Description("高阈值")]publicdoubleHeight{get;set;}=300;}
三 保存XML文件
privatevoidbutton1_Click(objectsender,EventArgse){DataModeldataModel=newDataModel();dataModel.Area=101;dataModel.Width=202;dataModel.Height=303;XmlSerializerHelper.WriteXML(dataModel,@"D:\\DataModel.xml",typeof(DataModel));}
四 读取XML文件
privatevoidbutton2_Click(objectsender,EventArgse){DataModeldataModel=newDataModel();dataModel=XmlSerializerHelper.ReadXML("testXmlDataModel.xml",typeof(TestXmlDataModel))asTestXmlDataModel;Doubletest1=Convert.ToDouble(dataModel.Area);Doubletest2=Convert.ToDouble(dataModel.Width);Doubletest3=Convert.ToDouble(dataModel.Height);propertyGrid1.SelectedObject=dataModel;}
五 propertyGrid1
DataModeldataModel=newDataModel();dataModel=XmlSerializerHelper.ReadXML("testXmlDataModel.xml",typeof(TestXmlDataModel))asTestXmlDataModel;Doubletest1=Convert.ToDouble(dataModel.Area);Doubletest2=Convert.ToDouble(dataModel.Width);Doubletest3=Convert.ToDouble(dataModel.Height);propertyGrid1.SelectedObject=dataModel;
![]()