我有一个方法可以为我完美地序列化数据:
public static string Serialize(BackgroundJobInfo info)
{
using (var stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
var writer = new XmlTextWriter(stringWriter);
var dataContractSerializer = new DataContractSerializer(typeof(BackgroundJobInfo),
null,
int.MaxValue,
true,
true,
new MySurrogate());
dataContractSerializer.WriteObject(writer, info);
return stringWriter.ToString();
}
}
但作为微软recommend我需要使用 XmlWriter
。
所以我改了一行:
var writer = XmlWriter.Create(stringWriter);
一切都坏了 - Serialize()
返回空字符串(而不是包含 xml 的字符串)
MySurrogate
包含一个方法
public object GetObjectToSerialize(object obj, Type targetType)
{
var maskedProperties = obj.GetType().GetProperties();
var setToNullProperties = maskedProperties.Where(m => m.GetCustomAttributes(typeof(DataMemberAttribute), true).Any() &&
m.GetCustomAttributes(typeof(DoNotSerializeAttribute), true).Any());
foreach (var member in setToNullProperties)
{
member.SetValue(obj, null, null);
}
return obj;
}
如何正确使用 XmlWriter
并解决我的问题?
最佳答案
您需要调用 Flush()
以强制 XmlWriter 将文本实际写入底层 TextWriter。
关于c# - 如何正确使用 XmlWriter.Create()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35845476/