How to Serialize any object to string using XmlSerializer for Webservices in C#(CSharp)

        public static string Serialize<T>(T dataObject)
        {
            StringBuilder sb = new StringBuilder();
            if (dataObject != null)
            {
                XmlSerializer xSer = new XmlSerializer(typeof(T));
                using (StringWriter sw = new StringWriter(sb))
                {
                    //for empty namespace
                    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                    ns.Add("", "");
 
                    xSer.Serialize(sw, dataObject, ns);
                    sw.Flush();
                }
            }
            return sb.ToString();
        }
person p = new person();
p.site = "w3mentor.com";
string profile =Serialize<person>(p);

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.