zoukankan      html  css  js  c++  java
  • XMLHelper

     private static XmlWriterSettings GetSettings()
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.NewLineChars = "
    ";
                settings.Encoding = Encoding.UTF8;
                return settings;
            }
    
            public static T ConvertToObject<T>(string filePath)
            {
                return ConvertToObject<T>(null, filePath);
            }
    
            public static T ConvertToObject<T>(Type instanceType, string filePath)
            {
                XmlSerializer ser = (instanceType == null) ? new XmlSerializer(typeof(T)) : new XmlSerializer(instanceType);
                XmlReader reader = XmlTextReader.Create(filePath);
    
                T instance;
                instance = (T)ser.Deserialize(reader);
                reader.Close();
    
                return instance;
            }
    
            public static void SaveToFile<T>(T instance, string filePath)
            {
                XmlSerializer ser = new XmlSerializer(typeof(T));
                XmlWriter writer = XmlTextWriter.Create(filePath, GetSettings());
                ser.Serialize(writer, instance);
                writer.Close();
                writer.Flush();
            }
            public static string SerializeToXml(object value)
            {
                if (value == null)
                    return "";
                string result = string.Empty;
                if (value is string)
                {
                    return value.ToString();
                }
    
                try
                {
                    StringBuilder sb = new StringBuilder(1000);
                    XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();
                    xmlns.Add(string.Empty, string.Empty);
    
                    XmlSerializer ser = new XmlSerializer(value.GetType());
                    using (TextWriter writer = new StringWriter(sb))
                    {
                        ser.Serialize(writer, value,xmlns);
                        result = writer.ToString();
                    }
                }
                catch
                {
                }
    
                return result;
            }
  • 相关阅读:
    【KVM系列 virt-v2v】virt-v2v过程中的报错
    大机与超级计算机的区别
    多路径 on linux
    ansible 管控 windows
    Linux启动盘
    RHCA 环境命令
    Xshell 4 连接 Ubuntu/Kali 报错 "找不到匹配的key exchange算法"
    security group & ACL
    windows powercfg
    OKD
  • 原文地址:https://www.cnblogs.com/Wolfmanlq/p/4183433.html
Copyright © 2011-2022 走看看