开发者

How to serialize a .NET object and assign to a string variable? [duplicate]

This question already has answers here: Can I Serialize XML straight to a string instead of a Stream with C#? (4 answers) Closed 6 years ago.

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

Example:

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

    XmlSerializer serializer =
    new XmlSerializer(typeof(OrderedItem));
    OrderedItem i = new OrderedItem();
    i.Ite开发者_StackOverflowmName = "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();

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


The easiest thing to do here is to use a StringWriter:

var sw = new StringWriter();
serializer.Serialize(sw, obj);
string xml = sw.ToString();


using (StringWriter sw = new StringWriter() && XmlSerializer xml = new XmlSerializer(typeof(OrderedItem)))
{
    xml.Serializer(sw, i);
    string result = sw.ToString();
}

This assumes that i is an OrderedItem (as per your post).


This is how I do it:

using(var mem = new MemoryStream()){
    serializer.Serialize(mem,"");
    String xml = Encoding.UTF8.GetString(mem.ToArray());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜