Mercurial > pub > bltoolkit
comparison Source/Mapping/MemberMappers/XMLSerialisationMapper.cs @ 0:f990fcb411a9
Копия текущей версии из github
author | cin |
---|---|
date | Thu, 27 Mar 2014 21:46:09 +0400 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:f990fcb411a9 |
---|---|
1 using System; | |
2 using System.IO; | |
3 using System.Xml; | |
4 using System.Xml.Serialization; | |
5 | |
6 namespace BLToolkit.Mapping.MemberMappers | |
7 { | |
8 public class XMLSerialisationMapper : MemberMapper | |
9 { | |
10 public override void SetValue(object o, object value) | |
11 { | |
12 if (value != null) this.MemberAccessor.SetValue(o, this.Deserialize(value.ToString())); | |
13 } | |
14 | |
15 public override object GetValue(object o) | |
16 { | |
17 return this.XmlSerialize(this.MemberAccessor.GetValue(o)); | |
18 } | |
19 | |
20 string XmlSerialize(object obj) | |
21 { | |
22 if (obj == null) return null; | |
23 XmlSerializer serializer = new XmlSerializer(this.Type); | |
24 MemoryStream ms = new MemoryStream(); | |
25 XmlWriterSettings settings = new XmlWriterSettings(); | |
26 settings.OmitXmlDeclaration = true; | |
27 settings.Indent = true; | |
28 XmlWriter writer = XmlWriter.Create(ms, settings); | |
29 XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(); | |
30 namespaces.Add(string.Empty, string.Empty); | |
31 serializer.Serialize(writer, obj, namespaces); | |
32 StreamReader r = new StreamReader(ms); | |
33 r.BaseStream.Seek(0, SeekOrigin.Begin); | |
34 | |
35 return r.ReadToEnd(); | |
36 } | |
37 | |
38 object Deserialize(string txt) | |
39 { | |
40 object retVal = null; | |
41 if (string.IsNullOrEmpty(txt)) return null; | |
42 | |
43 try | |
44 { | |
45 XmlSerializer ser = new XmlSerializer(this.Type); | |
46 StringReader stringReader = new StringReader(txt); | |
47 XmlTextReader xmlReader = new XmlTextReader(stringReader); | |
48 retVal = ser.Deserialize(xmlReader); | |
49 xmlReader.Close(); | |
50 stringReader.Close(); | |
51 } | |
52 catch (Exception) | |
53 { | |
54 } | |
55 return retVal; | |
56 } | |
57 } | |
58 } |