c# – 将Class转换为XML为string
发布时间:2020-12-16 01:48:19 所属栏目:百科 来源:网络整理
导读:我正在使用 XMLSerializer将类序列化为XML.有很多例子可以将XML保存到文件中.但是我想要的是将XML放入字符串而不是将其保存到文件中. 我正在尝试下面的代码,但它不起作用: public static void Main(string[] args) { XmlSerializer ser = new XmlSerializer
我正在使用
XMLSerializer将类序列化为XML.有很多例子可以将XML保存到文件中.但是我想要的是将XML放入字符串而不是将其保存到文件中.
我正在尝试下面的代码,但它不起作用: public static void Main(string[] args) { XmlSerializer ser = new XmlSerializer(typeof(TestClass)); MemoryStream m = new MemoryStream(); ser.Serialize(m,new TestClass()); string xml = new StreamReader(m).ReadToEnd(); Console.WriteLine(xml); Console.ReadLine(); } public class TestClass { public int Legs = 4; public int NoOfKills = 100; } 有想法该怎么解决这个吗 ? 谢谢. 解决方法
在读取之前,您必须将内存流放回到开头,如下所示:
XmlSerializer ser = new XmlSerializer(typeof(TestClass)); MemoryStream m = new MemoryStream(); ser.Serialize(m,new TestClass()); // reset to 0 so we start reading from the beginning of the stream m.Position = 0; string xml = new StreamReader(m).ReadToEnd(); 最重要的是,通过调用dispose或close来关闭资源始终很重要.您的完整代码应该是这样的: XmlSerializer ser = new XmlSerializer(typeof(TestClass)); string xml; using (MemoryStream m = new MemoryStream()) { ser.Serialize(m,new TestClass()); // reset to 0 m.Position = 0; xml = new StreamReader(m).ReadToEnd(); } Console.WriteLine(xml); Console.ReadLine(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |