类转换为XML字符串转换为、字符串、XML

由网友(1颗心为你适可而止)分享简介:我使用XMLSerializer的一类串行化为XML。有很多例子,这和XML保存到一个文件中。但我要的是把XML转换为字符串,而不是将其保存到一个文件中。I'm using XMLSerializer to serialize a class into a XML. There are plenty of examp...

我使用XMLSerializer的一类串行化为XML。有很多例子,这和XML保存到一个文件中。但我要的是把XML转换为字符串,而不是将其保存到一个文件中。

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.

我尝试用code以下,但它不工作:

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 ?

感谢。

推荐答案

您已经阅读这样的先定位您的内存流回到起点:

You have to position your memory stream back to the beginning prior to reading like this:

        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();

在最重要的是,它总是重要的通过调用处置或接近关闭的资源。你满code应该是这样的:

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:

        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();
阅读全文

相关推荐

最新文章