1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Xml;
- using System.Xml.Serialization;
- namespace Utils
- {
- public static class XmlUtils
- {
- /// <summary>
- /// 将object转换成xml格式的string
- /// </summary>
- /// <param name="o"></param>
- /// <returns></returns>
- public static string Object2XmlString(Object o)
- {
- XmlWriterSettings settings = new XmlWriterSettings();
- settings.Indent = false;
- settings.NewLineHandling = NewLineHandling.None;
- settings.Encoding = Encoding.UTF8;
- settings.OmitXmlDeclaration = true;
- XmlSerializer xs = new XmlSerializer(o.GetType());
- using (StringWriter ws = new StringWriter())
- {
- XmlWriter w = XmlWriter.Create(ws, settings);
- try
- {
- XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
- namespaces.Add(string.Empty, string.Empty);
- xs.Serialize(w, o, namespaces);
- return ws.ToString();
- } finally
- {
- w.Dispose();
- }
- }
- }
- /// <summary>
- /// 将xml格式的string转换层实体类
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="xmlStr"></param>
- /// <returns></returns>
- public static T XmlString2Object<T>(string xmlStr)
- {
- using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlStr)))
- {
- XmlSerializer serializer = new XmlSerializer(typeof(T));
- return (T)serializer.Deserialize(stream);
- }
- }
- /// <summary>
- /// 将xml格式stream转换层实体类
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="stream"></param>
- /// <returns></returns>
- public static T XmlStream2Object<T>(Stream stream)
- {
- XmlSerializer serializer = new XmlSerializer(typeof(T));
- return (T)serializer.Deserialize(stream);
- }
- /// <summary>
- /// 将xml格式文件转换层实体类
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="fileName"></param>
- /// <returns></returns>
- public static T XmlFile2Object<T>(string fileName)
- {
- using (Stream stream = new FileStream(fileName, FileMode.Open))
- {
- XmlSerializer serializer = new XmlSerializer(typeof(T));
- return (T)serializer.Deserialize(stream);
- }
- }
- }
- }
|