如何序列化 .NET 对象并分配给字符串变量? [英] How to serialize a .NET object and assign to a string variable?

查看:29
本文介绍了如何序列化 .NET 对象并分配给字符串变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 .NET 对象序列化为 XML 并将 XML 字符串分配给变量?

How do I serialize a .NET object into XML and assign the XML string to variable?

示例:

private void SerializeObject(string filename)
{
    Console.WriteLine("Writing With Stream");

    XmlSerializer serializer =
    new XmlSerializer(typeof(OrderedItem));
    OrderedItem i = new OrderedItem();
    i.ItemName = "Widget";
    i.Description = "Regular Widget";
    i.Quantity = 10;
    i.UnitPrice = (decimal) 2.30;
    i.Calculate();

    // Create a FileStream to write with.
    Stream writer = new FileStream(filename, FileMode.Create);

    // Serialize the object, and close the TextWriter
    serializer.Serialize(writer, i);

    //Assign the serialized XML to a variable here.
    //For example, var serialized=serializer.serialized(i);

    writer.Close();
}

推荐答案

XmlSerializer ser = new XmlSerializer(typeof(Test));
Test t = new Test() { Id = 1 };

MemoryStream ms = new MemoryStream();
ser.Serialize(ms, t);
ms.Position = 0;

StreamReader r = new StreamReader(ms);
string res = r.ReadToEnd();

编辑:@Quasdunk 不仅打败了我,而且还有更好的代码示例

EDIT: @Quasdunk not only beat me, but with a better code sample

这篇关于如何序列化 .NET 对象并分配给字符串变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆