Wednesday, October 17, 2012

Getting xml serialization in string c#, a usefule method, a generic method

public static string ToXml(object Obj)
        {
            XmlSerializer ser = new XmlSerializer(Obj.GetType());
            string xml;
 
            using (MemoryStream memStream = new MemoryStream())
            {
                XmlTextWriter xmlWriter = new XmlTextWriter(memStream, Encoding.UTF8);
                xmlWriter.Formatting = Formatting.Indented;
                xmlWriter.Indentation = 1;
                xmlWriter.IndentChar = Convert.ToChar(9);
                ser.Serialize(xmlWriter, Obj);
                xmlWriter.Close();
                memStream.Close();
                xml = Encoding.UTF8.GetString(memStream.GetBuffer());
                xml = xml.Substring(xml.IndexOf(Convert.ToChar(60)));
                xml = xml.Substring(0, (xml.LastIndexOf(Convert.ToChar(62)) + 1));
            }
            return xml;
        }

No comments:

Post a Comment