如何在 XmlTextWriter 和 XmlWriter 之间切换

本文关键字:之间 XmlWriter XmlTextWriter | 更新日期: 2023-09-27 18:37:07

Microsoft建议使用XmlWriter而不是XmlTextWriterhttps://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

如何在 XmlTextWriter 和 XmlWriter 之间切换

我会在XmlWriter类上使用工厂方法Create,如下所示:

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

你可以在没有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;
}