📜  将对象转换为 xml c# 示例代码 - C# 代码示例

📅  最后修改于: 2022-03-11 14:49:17.780000             🧑  作者: Mango

代码示例1
public class StringUtil
{
  
      public static string Serialize(object dataToSerialize)
        {
            if(dataToSerialize==null) return null;

            using (StringWriter stringwriter = new System.IO.StringWriter())
            {
                var serializer = new XmlSerializer(dataToSerialize.GetType());
                serializer.Serialize(stringwriter, dataToSerialize);
                return stringwriter.ToString();
            }
        }

        public static T Deserialize(string xmlText)
        {
            if(String.IsNullOrWhiteSpace(xmlText)) return default(T);

            using (StringReader stringReader = new System.IO.StringReader(xmlText))
            {
                var serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(stringReader);
            }
        }
}

//Note 
//StringUtil.Serialize(ObjClass); >> return xml
//StringUtil.Deserialize(str_xml); >> return object