的DataContractSerializer - 如何我可以输出的XML到字符串(而不是一个文件) [英] DataContractSerializer - how can I output the xml to a string (as opposed to a file)

查看:143
本文介绍了的DataContractSerializer - 如何我可以输出的XML到字符串(而不是一个文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

结果
我不得不对DataContractSerializer的一个简单的问题。也许它更是一个流问题。我发现了一段代码,将XML写入一个文件流。我基本上不想要的文件,只需要字符串输出


I had a quick question regarding the datacontractserializer. Maybe it's more of a stream question. I found a piece of code that writes the xml to a filestream. I basically don't want the file and just need the string output.

    public static string DataContractSerializeObject<T>(T objectToSerialize)
    {

        var fs = new FileStream("test.xml", FileMode.OpenOrCreate);
        var serializer = new DataContractSerializer(typeof(T));
        serializer.WriteObject(fs, objectToSerialize);
        fs.Close();
        return fs.ToString();
    }



fs.ToString()显然不是我要找的。什么流或作家等,我可以用刚返回正确的字符串,而不是创建一个文件?我没看FILESTREAM创建的XML,这正是我要找的。 XmlSerializer的写了XML有点怪怪的,我喜欢的DataContractSerializer的输出在这种情况下。任何人都可以点我在正确的方向?

fs.ToString() is obviously not what I'm looking for. What stream or writer etc, can I use just to return the proper string and not create a file? I did look at the XML the filestream created and it's exactly what I'm looking for. The XmlSerializer wrote the XML a bit strange and I prefer the output of the DataContractSerializer in this case. Can anyone point me in the right direction?

多谢,结果
〜CK在圣地亚哥

Thanks A Bunch,
~ck in San Diego

推荐答案

这样的事情 - 把你的输出转换成的MemoryStream ,然后读取,早在:

Something like this - put your output into a MemoryStream and then read that back in:

public static string DataContractSerializeObject<T>(T objectToSerialize)
{
    using(MemoryStream memStm = new MemoryStream())
    {
        var serializer = new DataContractSerializer(typeof(T));
        serializer.WriteObject(memStm, objectToSerialize);

        memStm.Seek(0, SeekOrigin.Begin);

        using(var streamReader = new StreamReader(memStm))
        {
             string result = streamReader.ReadToEnd();
             return result;
        }
    }
}

这篇关于的DataContractSerializer - 如何我可以输出的XML到字符串(而不是一个文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆