how to serialize a DataTable to json or xml

后端 未结 3 1179
情歌与酒
情歌与酒 2021-01-12 04:41

i\'m trying to serialize DataTable to Json or XML. is it possibly and how? any tutorials and ideas, please.

For example a have a sql table:

CREATE          


        
3条回答
  •  一个人的身影
    2021-01-12 05:33

    Let me try to answer your question. When it comes to serialization of a dataset or data table do not persist on to a file and readback.That causes IO overhead and is not viable in all scenarios. What you need to do is, write a function to Serialize the DataTable. (Make sure that you give a name to the DataTable inorder to serialize. See the example below in C#

    /*Use this method to serialize a given object in to XML. We will pass datatable in to this later */

        private XmlElement Serialize(object obj)
        {
            XmlElement serializedXmlElement = null;  
    
            try
            {
                System.IO.MemoryStream memoryStream = new MemoryStream();
                System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
                xmlSerializer.Serialize(memoryStream, obj);
                memoryStream.Position = 0;
    
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(memoryStream);
                serializedXmlElement = xmlDocument.DocumentElement;
            }
            catch (Exception e)
            {
                //logging statements. You must log exception for review
            }
    
            return serializedXmlElement; 
        }
    

    After you have implemented the Serialize method, you can serialize your DataTable as shown below. I am not writing my entire sample here for brevity.

            adapter.Fill(employee);
            employee.TableName = "Employees";
            XmlElement xmlElement = (XmlElement)Serialize(employee);
            Console.WriteLine(xmlElement.ToString());
            string xmlString = xmlElement.OuterXml.ToString();
    
            return xmlString;
    

    Hope this helps. Please let me know if you have more questions.

提交回复
热议问题