如何将.NET对象序列化为XML并将XML字符串分配给变量?
示例:
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();
}
答案 0 :(得分:2)
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不仅打败了我,还提供了更好的代码示例
答案 1 :(得分:1)
这里最简单的方法是使用StringWriter
:
var sw = new StringWriter();
serializer.Serializer(sw, obj);
string xml = sw.ToString();
答案 2 :(得分:0)
using (StringWriter sw = new StringWriter() && XmlSerializer xml = new XmlSerializer(typeof(OrderedItem)))
{
xml.Serializer(sw, i);
string result = sw.ToString();
}
这假定i
是OrderedItem
(根据您的帖子)。
答案 3 :(得分:-1)
我就是这样做的:
using(var mem = new MemoryStream()){
serializer.Serialize(mem,"");
String xml = Encoding.UTF8.GetString(mem.ToArray());
}