Home
Manage Your Code
Snippet: Save a collection of objects to XML as a string (C#)
Title: Save a collection of objects to XML as a string Language: C#
Description: Saves an collection of objects to xml and return the xml content as a string. Views: 388
Author: Kai Bohli Date Added: 2/26/2008
Copy Code  
1        private string SavePackageCollectionXMLAsString(object objGraph)
2        {
3            string sXML = string.Empty;
4            XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Package>));
5            using (StringWriter sw = new StringWriter())
6            {
7                xmlFormat.Serialize(sw, objGraph);
8                sXML = sw.ToString();
9                sw.Close();
10                return sXML;
11            }
12        }
13
Usage
            string sXML = string.Empty;

            Package pack1 = new Package();
            pack1.PackageNo = 1;

            Package pack2 = new Package();
            pack2.PackageNo = 2;

            List packages = new List();
            packages.Add(pack1);
            packages.Add(pack2);

            sXML = SavePackageCollectionXMLAsString(packages);