将各种格式的数据转换成XML

public class DataToXml
    {
       
        ///


        /// 将DataTable对象转换成XML字符串
        ///

        /// DataTable对象
        /// XML字符串
        public  string CDataTableToXml(DataTable dt)
        {
            if (dt != null)
            {
                MemoryStream ms = null;
                XmlTextWriter XmlWt = null;
                try
                {
                    ms = new MemoryStream();
                    //根据ms实例化XmlWt
                    XmlWt = new XmlTextWriter(ms, Encoding.Unicode);
                    //获取ds中的数据
                    dt.WriteXml(XmlWt);
                    int count = (int)ms.Length;
                    byte[] temp = new byte[count];
                    ms.Seek(0, SeekOrigin.Begin);
                    ms.Read(temp, 0, count);
                    //返回Unicode编码的文本
                    UnicodeEncoding ucode = new UnicodeEncoding();
                    string returnValue = ucode.GetString(temp).Trim();
                    return returnValue;
                }
                catch (System.Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    //释放资源
                    if (XmlWt != null)
                    {
                        XmlWt.Close();
                        ms.Close();
                        ms.Dispose();
                    }
                }
            }
            else
            {
                return "";
            }
        }

       
        ///


        /// 将DataSet对象中指定的Table转换成XML字符串
        ///

        /// DataSet对象
        /// DataSet对象中的Table索引
        /// XML字符串
        public  string CDataSetTableToXml(DataSet ds, int tableIndex)
        {
            if (tableIndex != -1)
            {
                return CDataTableToXml(ds.Tables[tableIndex]);
            }
            else
            {
                return CDataTableToXml(ds.Tables[0]);
            }
        }
       
        ///
        /// 将DataSet对象转换成XML字符串
        ///

        /// DataSet对象
        /// XML字符串
        public  string CDataSetToXml(DataSet ds)
        {
            return CDataSetTableToXml(ds, -1);
        }

       
        ///


        /// 将DataView对象转换成XML字符串
        ///

        /// DataView对象
        /// XML字符串
        public  string CDataViewToXml(DataView dv)
        {
            return CDataTableToXml(dv.Table);
        }
    }

转载于:https://www.cnblogs.com/hjianguo/p/5845097.html

你可能感兴趣的:(将各种格式的数据转换成XML)