-
Notifications
You must be signed in to change notification settings - Fork 0
/
XmlSerialization.cs
46 lines (42 loc) · 1.73 KB
/
XmlSerialization.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
namespace Gustav
{
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
class XmlSerialization
{
public string Serialize<T>(T source) where T : class
{
using (var memoryStream = new MemoryStream())
{
using (var streamWriter = XmlWriter.Create(memoryStream,
new XmlWriterSettings
{
OmitXmlDeclaration = true,
Encoding = Encoding.Unicode
}))
{
new XmlSerializer(typeof(T))
.Serialize(
streamWriter,
source,
new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }));
}
var xml = Encoding.Unicode.GetString(memoryStream.ToArray());
// XmlWriter adds character encoding code in the beginning of the memorystream
// that may cause problems when we will try to save result string in the database
// so we are deleting this code
return xml[0] != '\xfeff' ? xml : xml.Substring(1);
}
}
public T Deserialize<T>(string serialized) where T : class
{
using (var stringReader = new StringReader(serialized))
{
var xmlSerializer = new XmlSerializer(typeof(T));
return (T)xmlSerializer.Deserialize(stringReader);
}
}
}
}