实体、DataTable、json、xml互转

需要用到Newtonsoft.Json

		/// 
        /// 将xml转换datatabe
        /// 
        /// 
        /// 
        public static DataTable ConvertXMLToDataTable(string xmlData)
        {
            DataSet dsData = new DataSet();
            dsData.ReadXml(new XmlTextReader(new StringReader(xmlData)));
            DataTable dt = dsData.Tables["TableName"];
            return dt;
        }
        /// 
        /// 将datatable转换xml
        /// 
        /// 
        /// 
        public static string ConvertDataTableToXML(DataTable data)
        {
            MemoryStream stream = null;
            XmlTextWriter writer = null;
            try
            {
                DataSet ds = new DataSet("TableName");
                ds.Tables.Add(data.Copy());
                stream = new MemoryStream();
                writer = new XmlTextWriter(stream, Encoding.Unicode);
                ds.WriteXml(writer);
                int count = (int)stream.Length;
                byte[] arr = new byte[count];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(arr, 0, count);
                UnicodeEncoding utf = new UnicodeEncoding();
                string header = "" + "\r\n" +
                    "";
                string text = System.Text.Encoding.Unicode.GetString(arr, 2, count - 2);
                return String.Format("{0}\r\n{1}\r\n{2}", header , text , "");
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (writer != null)
                    writer.Close();
            }
        }
        /// 
        /// 实体转json
        /// 
        /// 
        /// 
        public static string ConvertObjectToJson(object obj)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            MemoryStream stream = new MemoryStream();
            serializer.WriteObject(stream, obj);
            byte[] dataBytes = new byte[stream.Length];
            stream.Position = 0;
            stream.Read(dataBytes, 0, (int)stream.Length);
            return Encoding.UTF8.GetString(dataBytes);
        }
        /// 
        /// xml转json
        /// 
        /// xml字符串
        /// 
        public static string ConvertXMLToJson(string xml)
        {
            string result = null;
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.LoadXml(xml);
            result = JsonConvert.SerializeXmlNode(xmldoc);
            return result;
        }
        /// 
        /// json转xml
        /// 
        /// 
        /// 
        public static string ConvertJsonToXml(string str)
        {
            XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(str), XmlDictionaryReaderQuotas.Max);
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);
            return doc.InnerXml;
        }
        //json转实体集合
        //var list = JsonConvert.DeserializeObject>(str);


		 /// 
        /// 实体类转换成DataTable
        /// 
        /// 实体类列表
        /// 
        public static DataTable ConvertTToDataTable<T>(List<T> list)
        {
            if (list == null || list.Count == 0)
            {
                return null;
            }
            DataTable dt = CreateData(list[0]);
            foreach (T model in list)
            {
                DataRow dataRow = dt.NewRow();
                foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
                {
                    dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null);
                }
                dt.Rows.Add(dataRow);
            }
            return dt;
        }

        //根据实体类得到表结构
        private DataTable CreateData<T>(T model)
        {
            DataTable dataTable = new DataTable(typeof(T).Name);
            foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
            {
                dataTable.Columns.Add(new DataColumn(propertyInfo.Name, propertyInfo.PropertyType));
            }
            return dataTable;
        }
		

        //-----------------------------------------------格式化分割线------------------------------------------------
		
		/// 
        /// 将字符串转换为xml格式
        /// 
        /// 
        /// 
        public static string FormatXML(string str)
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml(str);
            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
            System.IO.StringWriter stringWriter = new System.IO.StringWriter(stringBuilder);
            System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter(stringWriter);
            xmlWriter.Formatting = System.Xml.Formatting.Indented;
            doc.WriteTo(xmlWriter);
            return stringBuilder.ToString();
        }
        /// 
        /// 将字符串转换为json格式
        /// 
        /// 
        /// 
        public static string FormatJson(string str)
        {
            JsonSerializer serializer = new JsonSerializer();
            TextReader tr = new StringReader(str);
            JsonTextReader jtr = new JsonTextReader(tr);
            object obj = serializer.Deserialize(jtr);
            if (obj != null)
            {
                StringWriter textWriter = new StringWriter();
                JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                {
                    Formatting = Newtonsoft.Json.Formatting.Indented,
                    Indentation = 4,
                    IndentChar = ' '
                };
                serializer.Serialize(jsonWriter, obj);
                return textWriter.ToString();
            }
            else
            {
                return str;
            }
        }

你可能感兴趣的:(C#,.net,core,.net,json,xml,c#)