将类转换为 XML 到字符串
我正在使用 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;
}
关于如何解决这个问题有什么想法吗?
谢谢。
I'm using XMLSerializer to serialize a class into a XML. There are plenty of examples to this and save the XML into a file. However what I want is to put the XML into a string rather than save it to a file.
I'm experimenting with the code below, but it's not working:
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;
}
Any ideas on how to fix this ?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在读取之前,您必须将内存流放回开头,如下所示:
最重要的是,通过调用 dispose 或 close 来关闭资源始终很重要。你的完整代码应该是这样的:
You have to position your memory stream back to the beginning prior to reading like this:
On top of that, it's always important to close resources by either calling dispose or close. Your full code should be something like this:
TestClass 类缺少 [Serializabe] 属性,您必须将内存流的位置设置为开头:
There's the [Serializabe] attribute missing on class TestClass and you have to set the position of the memory stream to the beginning:
您的内存流未关闭,并且位于末尾(下一个可写入的位置)。我的猜测是你必须关闭它,或者寻找它的开头。按照您的方式,您不会阅读任何内容,因为您已经处于流的末尾。因此,在序列化对象之后添加 Seek()。像这样:
Your memory stream is not closed, and is positioned at the end (next available location to write in). My guess is that you must Close it, or Seek to its beginning. The way you do you don't read anything because you are already at the end of stream. So add Seek() after you serialize objects. Like this: