Blame view

Yi.Abp.Net8/framework/Yi.Framework.Core/Helper/XmlHelper.cs 1.45 KB
515fceeb   “wangming”   框架初始化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
  using System;
  using System.Collections.Generic;
  using System.IO;
  using System.Xml.Serialization;
  
  namespace Yi.Framework.Core.Helper
  {
      public class XmlHelper
      {
          /// <summary>
          /// 转换对象为JSON格式数据
          /// </summary>
          /// <typeparam name="T"></typeparam>
          /// <param name="obj">对象</param>
          /// <returns>字符格式的JSON数据</returns>
          public static string? GetXML<T>(object obj)
          {
              try
              {
                  XmlSerializer xs = new XmlSerializer(typeof(T));
  
                  using (TextWriter tw = new StringWriter())
                  {
                      xs.Serialize(tw, obj);
                      return tw.ToString();
                  }
              }
              catch (Exception)
              {
                  return string.Empty;
              }
          }
  
          /// <summary>
          /// Xml格式字符转换为T类型的对象
          /// </summary>
          /// <typeparam name="T"></typeparam>
          /// <param name="xml"></param>
          /// <returns></returns>
          public static T ParseFormByXml<T>(string xml, string rootName = "root")
          {
              XmlSerializer serializer = new XmlSerializer(typeof(T), new XmlRootAttribute(rootName));
              StringReader reader = new StringReader(xml);
  
              T res = (T)serializer.Deserialize(reader)!;
              reader.Close();
              reader.Dispose();
              return res;
          }
      }
  }