/
XmlSerializableSerializer.cs
48 lines (43 loc) · 1.51 KB
/
XmlSerializableSerializer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using ServiceStack.Text;
namespace ServiceStack.Serialization
{
public partial class XmlSerializableSerializer : IStringSerializer
{
public static XmlWriterSettings XmlWriterSettings { get; set; } = new XmlWriterSettings {
Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false),
};
public static XmlSerializableSerializer Instance = new XmlSerializableSerializer();
public string SerializeToString<XmlDto>(XmlDto from)
{
try
{
using (var ms = MemoryStreamFactory.GetStream())
{
using (XmlWriter xw = XmlWriter.Create(ms, XmlWriterSettings))
{
var ser = new XmlSerializerWrapper(from.GetType());
ser.WriteObject(xw, from);
}
return ms.ReadToEnd();
}
}
catch (Exception ex)
{
throw new SerializationException($"Error serializing object of type {from.GetType().FullName}", ex);
}
}
public void SerializeToStream(object obj, Stream stream)
{
using (var xw = XmlWriter.Create(stream, XmlWriterSettings))
{
var ser = new XmlSerializerWrapper(obj.GetType());
ser.WriteObject(xw, obj);
}
}
}
}