修正项目
This commit is contained in:
81
NX.ERP.U8.App/XmlHelper.cs
Normal file
81
NX.ERP.U8.App/XmlHelper.cs
Normal file
@@ -0,0 +1,81 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.IO;
|
||||
using System.Xml;
|
||||
using System.Xml.Serialization;
|
||||
|
||||
namespace U8AppMain
|
||||
{
|
||||
/// <summary>
|
||||
/// XML转化对象
|
||||
/// </summary>
|
||||
public static class XmlHelper
|
||||
{
|
||||
private static void XmlSerializeInternal(Stream stream, object o, Encoding encoding)
|
||||
{
|
||||
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
|
||||
ns.Add("", "");
|
||||
XmlSerializer serializer = new XmlSerializer(o.GetType());
|
||||
XmlWriterSettings settings = new XmlWriterSettings();
|
||||
settings.Indent = true;
|
||||
settings.NewLineChars = "\r\n";
|
||||
settings.Encoding = encoding;
|
||||
settings.IndentChars = " ";
|
||||
//settings.NamespaceHandling = NamespaceHandling.OmitDuplicates;
|
||||
using (XmlWriter writer = XmlWriter.Create(stream, settings))
|
||||
{
|
||||
serializer.Serialize(writer, o, ns);
|
||||
writer.Close();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将一个对象序列化为XML字符串
|
||||
/// </summary>
|
||||
/// <param name="o">要序列化的对象</param>
|
||||
/// <param name="encoding">编码方式</param>
|
||||
/// <returns>序列化产生的XML字符串</returns>
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="s"></param>
|
||||
/// <param name="encoding"></param>
|
||||
/// <returns></returns>
|
||||
public static T XmlDeserialize<T>(string s, Encoding encoding)
|
||||
{
|
||||
if (string.IsNullOrEmpty(s))
|
||||
throw new ArgumentNullException("s");
|
||||
if (encoding == null)
|
||||
throw new ArgumentNullException("encoding");
|
||||
|
||||
XmlSerializer mySerializer = new XmlSerializer(typeof(T));
|
||||
s = s.Replace(" ", " ");
|
||||
using (MemoryStream ms = new MemoryStream(encoding.GetBytes(s)))
|
||||
{
|
||||
using (StreamReader sr = new StreamReader(ms, encoding))
|
||||
{
|
||||
return (T)mySerializer.Deserialize(sr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user