using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace CommonUtility
{
public class SerializationXMLTool
{
public static string ObjectToXML(Object instance)
{
MemoryStream stream = null;
TextWriter writer = null;
try
{
stream = new MemoryStream(); // read xml in memory
writer = new StreamWriter(stream, Encoding.UTF8);
//Get serialise object
XmlSerializer serializer = new XmlSerializer(instance.GetType());
XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
xsn.Add(string.Empty, string.Empty);
serializer.Serialize(writer, instance, xsn); // read object
int count = (int)stream.Length; // saves object in memory stream
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
// copy stream contents in byte array
stream.Read(arr, 0, count);
UTF8Encoding utf = new UTF8Encoding();
return utf.GetString(arr).Trim();
}
catch (Exception ex)
{
//InterfaceLog.InterfaceERROR("序列化对象过程中出错!", ex);
throw new Exception(ex.ToString());
}
finally
{
if (stream != null && stream.Length > 0)
{
stream.Close();
}
if (writer != null)
{
writer.Close();
}
}
}
public static object XMLToObject(string xml, Type t)
{
StringReader stream = null;
XmlTextReader reader = null;
Object o;
try
{
XmlSerializer serializer = new XmlSerializer(t);
stream = new StringReader(xml); // read xml data
reader = new XmlTextReader(stream); // create reader
// covert reader to object
o = serializer.Deserialize(reader);
}
catch (Exception exp)
{
throw exp;
}
finally
{
if (stream != null)
{
stream.Close();
}
if (reader != null)
{
reader.Close();
}
}
return o;
}
/// <summary>
/// 将XMLDocment对象转化成对应的string
/// </summary>
/// <param name="xmldoc">需要被转化的XmlDocument对象</param>
/// <returns>转换后的字符串</returns>
public static string XMLDocmentToString(XmlDocument xmldoc)
{
MemoryStream ms = new MemoryStream();
XmlTextWriter tw = new XmlTextWriter(ms, Encoding.UTF8);
//tw.Formatting = Formatting.Indented;
//tw.Indentation = 4;
xmldoc.Save(tw);
byte[] ary = ms.ToArray();
string returnString = Encoding.UTF8.GetString(ary);
returnString = returnString.Substring(1, returnString.Length - 1);
return returnString;
}
}
}