0
|
1 ???using System; |
|
2 using System.Collections.Generic; |
|
3 using System.Text; |
|
4 using System.IO; |
|
5 |
|
6 namespace UCIS.Pml { |
|
7 public class PmlTextWriter : IPmlWriter { |
|
8 private TextWriter pWriter; |
|
9 |
|
10 public static string GetMessageString(PmlElement Message) { |
|
11 StringWriter Buffer = new StringWriter(); |
|
12 WriteMessageTo(Message, Buffer); |
|
13 return Buffer.ToString(); |
|
14 } |
|
15 |
|
16 public PmlTextWriter(TextWriter Writer) { |
|
17 pWriter = Writer; |
|
18 } |
|
19 public PmlTextWriter(Stream Writer, Encoding Encoding) { |
|
20 pWriter = new StreamWriter(Writer, Encoding); |
|
21 } |
|
22 public PmlTextWriter(StringBuilder StringBuilder) { |
|
23 pWriter = new StringWriter(StringBuilder); |
|
24 } |
|
25 |
|
26 public TextWriter BaseWriter { |
|
27 get { return pWriter; } |
|
28 set { pWriter = value; } |
|
29 } |
|
30 |
|
31 public void WriteMessage(PmlElement Message) { |
|
32 WriteElementTo(Message, "", pWriter); |
|
33 } |
|
34 |
|
35 public static void WriteMessageTo(PmlElement Message, TextWriter Writer) { |
|
36 lock (Writer) { |
|
37 WriteElementTo(Message, "", Writer); |
|
38 Writer.Flush(); |
|
39 } |
|
40 } |
|
41 |
|
42 private static void WriteElementTo(PmlElement Element, string Indent, TextWriter Writer) { |
|
43 if (Element == null) { |
|
44 Console.WriteLine("NULL"); |
|
45 return; |
|
46 } |
|
47 switch (Element.Type) { |
|
48 case PmlType.Null: |
|
49 Writer.WriteLine("NULL"); |
|
50 break; |
|
51 case PmlType.Collection: |
|
52 Writer.WriteLine("COLLECTION {"); |
|
53 foreach (PmlElement Child in (PmlCollection)Element) { |
|
54 Writer.Write(Indent + " "); |
|
55 WriteElementTo(Child, Indent + " ", Writer); |
|
56 } |
|
57 |
|
58 Writer.WriteLine(Indent + "}"); |
|
59 break; |
|
60 case PmlType.Dictionary: |
|
61 Writer.WriteLine("DICTIONARY {"); |
|
62 foreach (KeyValuePair<string, PmlElement> Child in (PmlDictionary)Element) { |
|
63 Writer.Write(Indent + " " + Uri.EscapeDataString(Child.Key) + " "); |
|
64 WriteElementTo(Child.Value, Indent + " ", Writer); |
|
65 } |
|
66 |
|
67 Writer.WriteLine(Indent + "}"); |
|
68 break; |
|
69 case PmlType.Binary: |
|
70 Writer.WriteLine("BINARY " + Convert.ToBase64String(Element.ToByteArray())); |
|
71 break; |
|
72 case PmlType.Integer: |
|
73 Writer.WriteLine("INT " + Element.ToString()); |
|
74 break; |
|
75 case PmlType.String: |
|
76 Writer.WriteLine("STRING " + Uri.EscapeDataString(Element.ToString())); |
|
77 break; |
|
78 } |
|
79 } |
|
80 } |
|
81 } |