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
?
答案 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;
}