如何在XmlTextWriter和XmlWriter之间切换?

时间:2016-03-02 16:41:38

标签: c#

Microsoft建议使用XmlWriter代替XmlTextWriter https://msdn.microsoft.com/en-us/library/system.xml.xmltextwriter(v=vs.110).aspx

public string Serialize(BackgroundJobInfo info)
{
    var stringBuilder = new StringBuilder();

    using (var stringWriter = new StringWriter(stringBuilder, CultureInfo.InvariantCulture))
    {
        var writer = new XmlTextWriter(stringWriter);
        new DataContractSerializer(typeof(BackgroundJobInfo)).WriteObject(writer, info);
    }

    return stringBuilder.ToString();
}

如何在我的方法中正确使用XmlWriter而不是XmlTextWriter

2 个答案:

答案 0 :(得分:3)

我在Create类上使用工厂方法XmlWriter,如:

var stringBuilder = new StringBuilder();
using(var writer = XmlWriter.Create(stringBuilder))
{
  new DataContractSerializer(typeof(BackgroundJobInfo)).WriteObject(writer, info)
}

答案 1 :(得分:0)

或者你可以在没有XmlWriter

的情况下完成
public static string Serialize(BackgroundJobInfo info)
{
    string result = String.Empty;

    using (var ms = new MemoryStream())
    {
        var sw = new StreamWriter(ms);

        DataContractSerializer dcs = new DataContractSerializer(typeof(BackgroundJobInfo));
        dcs.WriteObject(ms, info);
        sw.Flush();

        ms.Position = 0;
        var sr = new StreamReader(ms);
        result = sr.ReadToEnd();               
    }             

    return result;
}