我想为xml序列化创建常用函数但是有一个问题需要输入要序列化的对象,但我不知道它可以是什么类型的对象(persondetails或logindetails)我在这个例子中提到的任何东西和尝试修改但是typeof用红色下划线请帮帮我
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();
}
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;
}
}
答案 0 :(得分:0)
这是使用对象作为参数的Serialize函数的一个示例(您可以传递自己的类)。
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();
}
}