/
WddxSerializer.cs
94 lines (81 loc) · 2.67 KB
/
WddxSerializer.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using System;
using System.Xml;
using System.IO;
using System.Text;
namespace Mueller.Wddx
{
/// <summary>
/// This class is the main entry point for serializing any object into WDDX.
/// </summary>
public class WddxSerializer
{
private const string WDDXVERSION = "1.0";
private bool xmlDeclaration = false;
/// <summary>
/// Determines whether or not the XML processing declaration
/// (<?xml version="1.0"?>) is added to the WDDX packet.
/// Defaults to <c>false</c>.
/// </summary>
/// <remarks>
/// As of ColdFusion 5.0, CFWDDX cannot process the XML declaration.
/// </remarks>
public bool XmlDeclaration
{
get { return xmlDeclaration; }
set { xmlDeclaration = value; }
}
/// <summary>
/// Serializes an object to a string.
/// </summary>
/// <param name="obj">The object to be serialized.</param>
/// <returns>A string containing the WDDX packet.</returns>
public string Serialize(object obj)
{
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
XmlTextWriter writer = new XmlTextWriter(sw);
writer.Formatting = Formatting.None;
this.Serialize(writer, obj);
writer.Close();
}
return sb.ToString();
}
/// <summary>
/// Serializes an object to a pre-existing <see cref="XmlWriter"/> object.
/// </summary>
/// <remarks>
/// The <see cref="XmlWriter"/> should be pre-initialized, and can be pointed at many things:
/// a string, a file, a network stream, the ASP.NET Response stream, etc.
/// </remarks>
/// <param name="output">A pre-initialized <see cref="XmlWriter"/> object.</param>
/// <param name="obj">The object to be serialized.</param>
public void Serialize(XmlWriter output, object obj)
{
WritePacketHeader(output);
// write packet contents
WddxObjectSerializerFactory factory = new WddxObjectSerializerFactory();
IWddxObjectSerializer serializer = factory.GetSerializer(obj);
serializer.WriteObject(output, obj);
WritePacketFooter(output);
}
private void WritePacketHeader(XmlWriter output)
{
// CFWDDX doesn't like the XML declaration tag:
if (xmlDeclaration)
output.WriteStartDocument();
output.WriteStartElement("wddxPacket");
output.WriteAttributeString("version", WDDXVERSION);
output.WriteStartElement("header");
output.WriteEndElement();
output.WriteStartElement("data");
}
private void WritePacketFooter(XmlWriter output)
{
output.WriteEndElement(); // data
output.WriteEndElement(); // wddxPacket
if (xmlDeclaration)
output.WriteEndDocument();
}
}
}