如何正确使用XmlWriter.Create()?

时间:2016-03-07 13:50:02

标签: c#

我有一个方法可以为我完美地序列化数据:

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并解决我的问题?

1 个答案:

答案 0 :(得分:1)

您需要调用Flush()来强制XmlWriter将文本实际写入底层TextWriter。