سؤال

I want to create common function to xml serialization but there is a problem need to typeof object that to be serialise but I don't know the type of object it can be (persondetails or logindetails) anything i reffered this example and trying to modify but typeof is underlineing with red please help me

original

static public void SerializeToXML(Movie movie)
{  
  XmlSerializer serializer = new XmlSerializer(typeof(Movie));
  TextWriter textWriter = new StreamWriter(@"C:\movie.xml");
    serializer.Serialize(textWriter, movie);
    textWriter.Close();
}

My code

public class XmlSerialization
{

    static public string SerializeToXML("What type have to put here")
    {
        string xmlReturn="";
        XmlSerializer serializer = new XmlSerializer(typeof("What type have to put here"));
        TextWriter textWriter = new StreamWriter(xmlReturn);
        serializer.Serialize(textWriter, xml);
        textWriter.Close();

        return xmlReturn;
    }
}
هل كانت مفيدة؟

المحلول

This is an example of Serialize funcion that use a object as a parameter (you could pass your own class).

public string Serialize(Object process)
        {
            MemoryStream stream = null;
            TextWriter writer = null;

            try
            {
                stream = new MemoryStream();
                writer = new StreamWriter(stream, Encoding.Unicode);

                XmlSerializer serializer = new XmlSerializer(process.GetType());

                serializer.Serialize(writer, process);
                int count = (int)stream.Length;
                byte[] arr = new byte[count];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(arr, 0, count);
                UnicodeEncoding utf = new UnicodeEncoding();
                return utf.GetString(arr).Trim();
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
            finally
            {
                if (stream != null) stream.Close();
                if (writer != null) writer.Close();
            }
        }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top