using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Globalization;
using System.IO.Compression;
namespace BaseLibRWFile
{
///
/// XMLHelper
///
public class XMLHelper
{
///
/// Creates the specified node name.
///
/// Name of the node.
/// XmlNode.
public static XmlNode Create(string nodeName)
{
var doc = new XmlDocument();
XmlNode node = doc.CreateElement(nodeName);
return node;
}
///
/// Creates the attribute.
///
/// The node.
/// Name of the attribute.
/// The value.
/// XmlAttribute.
public static XmlAttribute CreateAttribute(XmlNode node, string attributeName, string value)
{
try
{
XmlDocument doc = node.OwnerDocument;
XmlAttribute attr = doc.CreateAttribute(attributeName);
attr.Value = value;
node.Attributes.SetNamedItem(attr);
return attr;
}
catch (Exception err)
{
string desc = err.Message;
return null;
}
}
///
/// Objects to XML.
///
/// The configuration.
/// XmlNode.
public static XmlNode ObjectToXML(object config)
{
try
{
var xnd = new XmlDocument();
if (config != null)
{
//we need the type to serialize
Type t = config.GetType();
var ser = new XmlSerializer(t);
//will hold the xml
using (var writer = new StringWriter(CultureInfo.InvariantCulture))
{
ser.Serialize(writer, config);
xnd.LoadXml(writer.ToString());
writer.Close();
}
}
return xnd.DocumentElement;
}
catch
{
throw;
}
}
///
/// XMLs to object.
///
/// The node.
/// Type of the object.
/// System.Object.
public static object XMLToObject(XmlNode node, Type objectType)
{
object convertedObject = null;
if (node != null)
{
using (var reader = new StringReader(node.OuterXml))
{
var ser = new XmlSerializer(objectType);
convertedObject = ser.Deserialize(reader);
reader.Close();
}
}
return convertedObject;
}
}
///
/// Class XmlSerializerHelper.
///
public class ClsXml
{
///
/// 读取XML文件
///
/// The XML file path.
/// The type.
/// System.Object.
public static object ReadXML(string XmlFilePath, Type type)
{
object object4Read = null;
var serializer = new XmlSerializer(type);
if (!File.Exists(XmlFilePath))
{
return new object();
}
while (object4Read == null)
{
var stream = new FileStream(XmlFilePath, FileMode.Open);
try
{
object4Read = serializer.Deserialize(stream);
}
finally
{
stream.Close();
}
}
return object4Read;
}
///
/// 序列化XML文件
///
/// My ds.
/// The XML file path.
/// The type.
/// true if XXXX, false otherwise.
public static bool WriteXML(object myDs, string XmlFilePath, Type type)
{
bool flag = true;
StreamWriter writer = null;
var serializer = new XmlSerializer(type);
try
{
writer = new StreamWriter(XmlFilePath, false);
serializer.Serialize(writer, myDs);
}
catch (Exception)
{
flag = false;
}
finally
{
if (writer != null)
{
writer.Close();
}
}
return flag;
}
///
/// XMLs the serialize.
///
///
/// The entity.
/// System.String.
public static string XMLSerialize(T entity)
{
var buffer = new StringBuilder();
var serializer = new XmlSerializer(typeof(T));
using (TextWriter writer = new StringWriter(buffer))
{
serializer.Serialize(writer, entity);
}
return buffer.ToString();
}
///
/// Des the XML serialize.
///
///
/// The XML string.
/// T.
public static T DeXMLSerialize(string xmlString)
{
T cloneObject = default(T);
var buffer = new StringBuilder();
buffer.Append(xmlString);
var serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StringReader(buffer.ToString()))
{
Object obj = serializer.Deserialize(reader);
cloneObject = (T)obj;
}
return cloneObject;
}
///
/// 把对象序列化为字符串
///
/// The p object.
/// System.Byte[].
public static byte[] SerializeObject(object pObj)
{
if (pObj == null)
return null;
var _memory = new MemoryStream();
var formatter = new BinaryFormatter();
formatter.Serialize(_memory, pObj);
_memory.Position = 0;
var read = new byte[_memory.Length];
_memory.Read(read, 0, read.Length);
_memory.Close();
return Compress(read);
}
///
/// 把字节反序列化成相应的对象
///
/// 字节流
/// object
public static object DeserializeObject(byte[] pBytes)
{
object _newOjb = null;
if (pBytes == null)
return _newOjb;
var _memory = new MemoryStream(Decompress(pBytes));
_memory.Position = 0;
var formatter = new BinaryFormatter();
_newOjb = formatter.Deserialize(_memory);
_memory.Close();
return _newOjb;
}
///
/// Write byte[] to file
///
/// The data source.
/// The file path.
public static void WriteByteToFile(byte[] dataSource, string filePath)
{
var fs = new FileStream(filePath, FileMode.Create);
//将byte数组写入文件中
fs.Write(dataSource, 0, dataSource.Length);
fs.Close();
}
///
/// Read byte from file
///
/// The file path.
/// System.Byte[].
public static byte[] ReadByteFromFile(string filePath)
{
var fs = new FileStream(filePath, FileMode.Open);
//获取文件大小
long size = fs.Length;
var array = new byte[size];
//将文件读到byte数组中
fs.Read(array, 0, array.Length);
fs.Close();
return array;
}
///
/// Write object to file
///
/// The data source.
/// The file path.
public static void WriteObjectToFile(object dataSource, string filePath)
{
var fs = new FileStream(filePath, FileMode.Create);
byte[] arraysource = SerializeObject(dataSource);
//将byte数组写入文件中
fs.Write(arraysource, 0, arraysource.Length);
fs.Close();
}
///
/// Read object from file
///
/// The file path.
/// System.Object.
public static object ReadObjectFromFile(string filePath)
{
var fs = new FileStream(filePath, FileMode.Open);
//获取文件大小
long size = fs.Length;
var array = new byte[size];
//将文件读到byte数组中
fs.Read(array, 0, array.Length);
fs.Close();
return DeserializeObject(array);
}
///
/// 字符串压缩
///
/// The data.
/// System.Byte[].
///
public static byte[] Compress(byte[] data)
{
try
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Compress, true);
zip.Write(data, 0, data.Length);
zip.Close();
var buffer = new byte[ms.Length];
ms.Position = 0;
ms.Read(buffer, 0, buffer.Length);
ms.Close();
return buffer;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
///
/// 字符串解压缩
///
/// The data.
/// System.Byte[].
///
public static byte[] Decompress(byte[] data)
{
try
{
var ms = new MemoryStream(data);
var zip = new GZipStream(ms, CompressionMode.Decompress, true);
var msreader = new MemoryStream();
var buffer = new byte[0x1000];
while (true)
{
int reader = 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();
return buffer;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
///
/// string 压缩
///
/// The string.
/// System.String.
public static string CompressString(string str)
{
string compressString = "";
byte[] compressBeforeByte = Encoding.GetEncoding("UTF-8").GetBytes(str);
byte[] compressAfterByte = Compress(compressBeforeByte);
//compressString = Encoding.GetEncoding("UTF-8").GetString(compressAfterByte);
compressString = Convert.ToBase64String(compressAfterByte);
return compressString;
}
///
/// string 解压缩
///
/// The string.
/// System.String.
public static string DecompressString(string str)
{
string compressString = "";
//byte[] compressBeforeByte = Encoding.GetEncoding("UTF-8").GetBytes(str);
byte[] compressBeforeByte = Convert.FromBase64String(str);
byte[] compressAfterByte = Decompress(compressBeforeByte);
compressString = Encoding.GetEncoding("UTF-8").GetString(compressAfterByte);
return compressString;
}
///
/// XMLs the serialize internal.
///
/// The stream.
/// The o.
/// The encoding.
private static void XmlSerializeInternal(Stream stream, object o, Encoding encoding)
{
if (o == null)
throw new ArgumentNullException(nameof(o));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
XmlSerializer serializer = new XmlSerializer(o.GetType());
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.NewLineChars = "\r\n";
settings.Encoding = encoding;
settings.IndentChars = " ";
using (XmlWriter writer = XmlWriter.Create(stream, settings))
{
serializer.Serialize(writer, o);
writer.Close();
}
}
///
/// 将一个对象序列化为XML字符串
///
/// 要序列化的对象
/// 编码方式
/// 序列化产生的XML字符串
public static string XmlSerialize(object o, Encoding encoding)
{
using (MemoryStream stream = new MemoryStream())
{
XmlSerializeInternal(stream, o, encoding);
stream.Position = 0;
using (StreamReader reader = new StreamReader(stream, encoding))
{
return reader.ReadToEnd();
}
}
}
///
/// 将一个对象按XML序列化的方式写入到一个文件
///
/// 要序列化的对象
/// 保存文件路径
/// 编码方式
public static void XmlSerializeToFile(object o, string path, Encoding encoding)
{
if (string.IsNullOrEmpty(path))
throw new ArgumentNullException(nameof(path));
using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write))
{
XmlSerializeInternal(file, o, encoding);
}
}
///
/// 从XML字符串中反序列化对象
///
/// 结果对象类型
/// 包含对象的XML字符串
/// 编码方式
/// 反序列化得到的对象
public static T XmlDeserialize(string s, Encoding encoding)
{
if (string.IsNullOrEmpty(s))
throw new ArgumentNullException(nameof(s));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
XmlSerializer mySerializer = new XmlSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream(encoding.GetBytes(s)))
{
using (StreamReader sr = new StreamReader(ms, encoding))
{
return (T)mySerializer.Deserialize(sr);
}
}
}
///
/// 读入一个文件,并按XML的方式反序列化对象。
///
/// 结果对象类型
/// 文件路径
/// 编码方式
public static T XmlDeserializeFromFile(string path, Encoding encoding)
{
if (string.IsNullOrEmpty(path))
throw new ArgumentNullException(nameof(path));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
string xml = File.ReadAllText(path, encoding);
return XmlDeserialize(xml, encoding);
}
///
/// XMLs the configuration writer.
///
///
/// The object.
/// The path.
public static void XmlConfigWriter(T obja, string path)
{
try
{
using (StreamWriter sw = new StreamWriter(path))
{
Type t = obja.GetType();
XmlSerializer serializer = new XmlSerializer(obja.GetType());
serializer.Serialize(sw, obja);
sw.Close();
}
}
catch (Exception e)
{
e.ToString();
}
}
///
/// XMLs the configuration reader.
///
/// The file path.
/// The type.
/// System.Object.
public static object XmlConfigReader(string filePath, Type type)
{
object result = null;
try
{
if (File.Exists(filePath))
{
using (StreamReader reader = new StreamReader(filePath))
{
XmlSerializer xmlSerializer = new XmlSerializer(type);
result = xmlSerializer.Deserialize(reader);
}
}
return result;
}
catch (Exception e)
{
return e;
}
}
}
}