Reputation:
I have a method that perfectly serialize data for me:
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();
}
}
But as Microsoft recommend I need to use XmlWriter
.
So I change one line:
var writer = XmlWriter.Create(stringWriter);
And everything broken - Serialize()
return empty string (instead of string that contains xml)
MySurrogate
contains a method
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;
}
How to correctly use XmlWriter
and fix my problem?
Upvotes: 2
Views: 763
Reputation: 888203
You need to call Flush()
to force the XmlWriter to actually write the text to the underlying TextWriter.
Upvotes: 1