1. 程式人生 > >將DataTable轉換為Xml,以及互轉換

將DataTable轉換為Xml,以及互轉換

        private string ConvertDataTableToXML(DataSet ods)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                //XmlReader xx=new XmlRead
                using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Default))
                {
                    try
                    {                      
                        ods.WriteXml(writer, XmlWriteMode.WriteSchema);
                        byte[] bytes = new byte[(int)stream.Length];
                        stream.Seek(0, SeekOrigin.Begin);
                        stream.Read(bytes, 0, (int)stream.Length);
                        return System.Text.Encoding.Default.GetString(bytes);
                    }
                    catch(Exception err)
                    {
                        return err.Message;
                    }
                }
            }
        }





        private DataSet ConvertXMLToDataSet(string data)
        {
            using (StringReader stream = new StringReader(data))
            {
                using (XmlReader reader = XmlReader.Create(stream))
                {
                    try
                    {
                        DataSet ds = new DataSet();
                        ds.ReadXml(reader);
                        if (ds.Tables.Count > 0)
                            return ds;
                        else
                            return null;
                    }
                    catch
                    {
                        return null;
                    }
                }
            }
        }