Welcome to mirror list, hosted at ThFree Co, Russian Federation.

XmlTextWriter.cs « System.Xml « System.XML « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a598695b306666a6b7319b0984baa9a0caf5593a (plain)
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
//
// System.Xml.XmlTextWriter
//
// Author:
//   Kral Ferch <kral_ferch@hotmail.com>
//
// (C) 2002 Kral Ferch
//

using System;
using System.Collections;
using System.IO;
using System.Text;

namespace System.Xml
{
	public class XmlTextWriter : XmlWriter
	{
		#region Fields

		protected TextWriter w;
		protected bool nullEncoding = false;
		protected bool openWriter = true;
		protected bool openStartElement = false;
		protected bool openStartAttribute = false;
		protected bool documentStarted = false;
		private bool namespaces = true;
		protected bool openAttribute = false;
		protected bool attributeWrittenForElement = false;
		protected Stack openElements = new Stack ();
		private Formatting formatting = Formatting.None;
		private int indentation = 2;
		private char indentChar = ' ';
		protected string indentChars = "  ";
		private char quoteChar = '\"';
		protected int indentLevel = 0;
		protected string indentFormatting;
		protected Stream baseStream = null;
		protected string xmlLang = null;
		protected XmlSpace xmlSpace = XmlSpace.None;
		protected bool openXmlLang = false;
		protected bool openXmlSpace = false;

		#endregion

		#region Constructors

		public XmlTextWriter (TextWriter w) : base ()
		{
			this.w = w;
			
			try {
				baseStream = ((StreamWriter)w).BaseStream;
			}
			catch (Exception) { }
		}

		public XmlTextWriter (Stream w,	Encoding encoding) : base ()
		{
			if (encoding == null) {
				nullEncoding = true;
				encoding = new UTF8Encoding ();
			}

			this.w = new StreamWriter(w, encoding);
			baseStream = w;
		}

		public XmlTextWriter (string filename, Encoding encoding) : base ()
		{
			this.w = new StreamWriter(filename, false, encoding);
			baseStream = ((StreamWriter)w).BaseStream;
		}

		#endregion

		#region Properties

		public Stream BaseStream {
			get { return baseStream; }
		}


		public Formatting Formatting {
			get { return formatting; }
			set { formatting = value; }
		}

		public bool IndentingOverriden 
		{
			get {
				if (openElements.Count == 0)
					return false;
				else
					return (((XmlTextWriterOpenElement)openElements.Peek()).IndentingOverriden);
			}
			set {
				if (openElements.Count > 0)
					((XmlTextWriterOpenElement)openElements.Peek()).IndentingOverriden = value;
			}
		}

		public int Indentation {
			get { return indentation; }
			set {
				indentation = value;
				UpdateIndentChars ();
			}
		}

		public char IndentChar {
			get { return indentChar; }
			set {
				indentChar = value;
				UpdateIndentChars ();
			}
		}

		public bool Namespaces {
			get { return namespaces; }
			set {
				if (ws != WriteState.Start)
					throw new InvalidOperationException ("NotInWriteState.");
				
				namespaces = value;
			}
		}

		public char QuoteChar {
			get { return quoteChar; }
			set {
				if ((value != '\'') && (value != '\"'))
					throw new ArgumentException ("This is an invalid XML attribute quote character. Valid attribute quote characters are ' and \".");
				
				quoteChar = value;
			}
		}

		public override WriteState WriteState {
			get { return ws; }
		}
		
		public override string XmlLang {
			get {
				string xmlLang = null;
				int i;

				for (i = 0; i < openElements.Count; i++) 
				{
					xmlLang = ((XmlTextWriterOpenElement)openElements.ToArray().GetValue(i)).XmlLang;
					if (xmlLang != null)
						break;
				}

				return xmlLang;
			}
		}

		public override XmlSpace XmlSpace {
			get {
				XmlSpace xmlSpace = XmlSpace.None;
				int i;

				for (i = 0; i < openElements.Count; i++) 
				{
					xmlSpace = ((XmlTextWriterOpenElement)openElements.ToArray().GetValue(i)).XmlSpace;
					if (xmlSpace != XmlSpace.None)
						break;
				}

				return xmlSpace;
			}
		}

		#endregion

		#region Methods

		private void CheckState ()
		{
			if (!openWriter) {
				throw new InvalidOperationException ("The Writer is closed.");
			}

			if ((documentStarted == true) && (formatting == Formatting.Indented) && (!IndentingOverriden)) {
				indentFormatting = "\r\n";
				if (indentLevel > 0) {
					for (int i = 0; i < indentLevel; i++)
						indentFormatting += indentChars;
				}
			}
			else
				indentFormatting = "";

			documentStarted = true;
		}

		public override void Close ()
		{
			CloseOpenAttributeAndElements ();

			w.Close();
			ws = WriteState.Closed;
			openWriter = false;
		}

		private void CloseOpenAttributeAndElements ()
		{
			if (openAttribute)
				WriteEndAttribute ();

			while (openElements.Count > 0) {
				WriteEndElement();
			}
		}

		private void CloseStartElement ()
		{
			if (openStartElement) {
				w.Write(">");
				ws = WriteState.Content;
				openStartElement = false;
				attributeWrittenForElement = false;
			}
		}

		public override void Flush ()
		{
			w.Flush ();
		}

		public override string LookupPrefix (string ns)
		{
			string prefix = namespaceManager.LookupPrefix (ns);

			if (prefix == String.Empty)
				prefix = null;

			return prefix;
		}

		private void UpdateIndentChars ()
		{
			indentChars = "";
			for (int i = 0; i < indentation; i++)
				indentChars += indentChar;
		}

		public override void WriteBase64 (byte[] buffer, int index, int count)
		{
			w.Write (Convert.ToBase64String (buffer, index, count));
		}

		[MonoTODO]
		public override void WriteBinHex (byte[] buffer, int index, int count)
		{
			throw new NotImplementedException ();
		}

		public override void WriteCData (string text)
		{
			if (text.IndexOf("]]>") > 0)
				throw new ArgumentException ();

			CheckState ();
			CloseStartElement ();

			w.Write("<![CDATA[{0}]]>", text);
		}

		public override void WriteCharEntity (char ch)
		{
			Int16	intCh = (Int16)ch;

			// Make sure the character is not in the surrogate pair
			// character range, 0xd800- 0xdfff
			if ((intCh >= -10240) && (intCh <= -8193))
				throw new ArgumentException ("Surrogate Pair is invalid.");

			w.Write("&#x{0:X};", intCh);
		}

		[MonoTODO]
		public override void WriteChars (char[] buffer, int index, int count)
		{
			throw new NotImplementedException ();
		}

		public override void WriteComment (string text)
		{
			if ((text.EndsWith("-")) || (text.IndexOf("-->") > 0)) {
				throw new ArgumentException ();
			}

			CheckState ();
			CloseStartElement ();

			w.Write ("<!--{0}-->", text);
		}

		[MonoTODO]
		public override void WriteDocType (string name, string pubid, string sysid, string subset)
		{
			throw new NotImplementedException ();
		}

		public override void WriteEndAttribute ()
		{
			if (!openAttribute)
				throw new InvalidOperationException("Token EndAttribute in state Start would result in an invalid XML document.");

			CheckState ();

			if (openXmlLang) {
				w.Write (xmlLang);
				openXmlLang = false;
				((XmlTextWriterOpenElement)openElements.Peek()).XmlLang = xmlLang;
			}

			if (openXmlSpace) 
			{
				w.Write (xmlSpace.ToString ().ToLower ());
				openXmlSpace = false;
				((XmlTextWriterOpenElement)openElements.Peek()).XmlSpace = xmlSpace;
			}

			w.Write ("{0}", quoteChar);

			openAttribute = false;
		}

		public override void WriteEndDocument ()
		{
			if ((ws == WriteState.Start) || (ws == WriteState.Prolog))
				throw new ArgumentException ("This document does not have a root element.");

			CloseOpenAttributeAndElements ();

			ws = WriteState.Start;
		}

		public override void WriteEndElement ()
		{
			WriteEndElementInternal (false);
		}

		private void WriteEndElementInternal (bool fullEndElement)
		{
			if (openElements.Count == 0)
				throw new InvalidOperationException("There was no XML start tag open.");

			indentLevel--;

			CheckState ();

			if (openStartElement) {
				if (openAttribute)
					WriteEndAttribute ();

				if (fullEndElement)
					w.Write ("></{0}>", ((XmlTextWriterOpenElement)openElements.Peek ()).Name);
				else
					w.Write (" />");

				openElements.Pop ();
				openStartElement = false;
			} else {
				w.Write ("{0}</{1}>", indentFormatting, openElements.Pop ());
			}

			namespaceManager.PopScope();
		}

		[MonoTODO]
		public override void WriteEntityRef (string name)
		{
			throw new NotImplementedException ();
		}

		public override void WriteFullEndElement ()
		{
			WriteEndElementInternal (true);
		}

		[MonoTODO]
		public override void WriteName (string name)
		{
			throw new NotImplementedException ();
		}

		[MonoTODO]
		public override void WriteNmToken (string name)
		{
			throw new NotImplementedException ();
		}

		public override void WriteProcessingInstruction (string name, string text)
		{
			if ((name == null) || (name == string.Empty) || (name.IndexOf("?>") > 0) || (text.IndexOf("?>") > 0)) {
				throw new ArgumentException ();
			}

			CheckState ();
			CloseStartElement ();

			w.Write ("{0}<?{1} {2}?>", indentFormatting, name, text);
		}

		[MonoTODO]
		public override void WriteQualifiedName (string localName, string ns)
		{
			throw new NotImplementedException ();
		}

		public override void WriteRaw (string data)
		{
			WriteStringInternal (data, false);
		}

		[MonoTODO]
		public override void WriteRaw (char[] buffer, int index, int count)
		{
			throw new NotImplementedException ();
		}

		public override void WriteStartAttribute (string prefix, string localName, string ns)
		{
			if ((prefix == "xml") && (localName == "lang"))
				openXmlLang = true;

			if ((prefix == "xml") && (localName == "space"))
				openXmlSpace = true;

			if ((prefix == "xmlns") && (localName == "xmlns"))
				throw new ArgumentException ("Prefixes beginning with \"xml\" (regardless of whether the characters are uppercase, lowercase, or some combination thereof) are reserved for use by XML.");

			CheckState ();

			if (ws == WriteState.Content)
				throw new InvalidOperationException ("Token StartAttribute in state " + WriteState + " would result in an invalid XML document.");

			if (prefix == null)
				prefix = String.Empty;

			if (ns == null)
				ns = String.Empty;

			string formatPrefix = "";
			string formatSpace = "";

			if (ns != String.Empty) 
			{
				string existingPrefix = namespaceManager.LookupPrefix (ns);

				if (prefix == String.Empty)
					prefix = existingPrefix;
			}

			if (prefix != String.Empty) 
			{
				formatPrefix = prefix + ":";
			}

			if (openStartElement || attributeWrittenForElement)
				formatSpace = " ";

			w.Write ("{0}{1}{2}={3}", formatSpace, formatPrefix, localName, quoteChar);

			openAttribute = true;
			attributeWrittenForElement = true;
			ws = WriteState.Attribute;
		}

		public override void WriteStartDocument ()
		{
			WriteStartDocument ("");
		}

		public override void WriteStartDocument (bool standalone)
		{
			string standaloneFormatting;

			if (standalone == true)
				standaloneFormatting = String.Format (" standalone={0}yes{0}", quoteChar);
			else
				standaloneFormatting = String.Format (" standalone={0}no{0}", quoteChar);

			WriteStartDocument (standaloneFormatting);
		}

		private void WriteStartDocument (string standaloneFormatting)
		{
			if (documentStarted == true)
				throw new InvalidOperationException("WriteStartDocument should be the first call.");

			CheckState ();

			string encodingFormatting = "";

			if (!nullEncoding)
				encodingFormatting = String.Format (" encoding={0}{1}{0}", quoteChar, w.Encoding.HeaderName);

			w.Write("<?xml version={0}1.0{0}{1}{2}?>", quoteChar, encodingFormatting, standaloneFormatting);
			ws = WriteState.Prolog;
		}

		public override void WriteStartElement (string prefix, string localName, string ns)
		{
			if (!Namespaces && (((prefix != null) && (prefix != String.Empty))
				|| ((ns != null) && (ns != String.Empty))))
				throw new ArgumentException ("Cannot set the namespace if Namespaces is 'false'.");

			WriteStartElementInternal (prefix, localName, ns);
		}

		protected override void WriteStartElementInternal (string prefix, string localName, string ns)
		{
			if (prefix == null)
				prefix = String.Empty;

			if (ns == null)
				ns = String.Empty;

			if ((prefix != String.Empty) && ((ns == null) || (ns == String.Empty)))
				throw new ArgumentException ("Cannot use a prefix with an empty namespace.");

			CheckState ();
			CloseStartElement ();

			string formatXmlns = "";
			string formatPrefix = "";

			if (ns != String.Empty) 
			{
				string existingPrefix = namespaceManager.LookupPrefix (ns);

				if (prefix == String.Empty)
					prefix = existingPrefix;

				if (prefix != existingPrefix)
					formatXmlns = String.Format (" xmlns:{0}={1}{2}{1}", prefix, quoteChar, ns);
				else if (existingPrefix == String.Empty)
					formatXmlns = String.Format (" xmlns={0}{1}{0}", quoteChar, ns);
			}
			else if ((prefix == String.Empty) && (namespaceManager.LookupNamespace(prefix) != String.Empty)) {
				formatXmlns = String.Format (" xmlns={0}{0}", quoteChar);
			}

			if (prefix != String.Empty) {
				formatPrefix = prefix + ":";
			}

			w.Write ("{0}<{1}{2}{3}", indentFormatting, formatPrefix, localName, formatXmlns);

			openElements.Push (new XmlTextWriterOpenElement (formatPrefix + localName));
			ws = WriteState.Element;
			openStartElement = true;

			namespaceManager.PushScope ();
			namespaceManager.AddNamespace (prefix, ns);

			indentLevel++;
		}

		public override void WriteString (string text)
		{
			if (ws == WriteState.Prolog)
				throw new InvalidOperationException ("Token content in state Prolog would result in an invalid XML document.");

			WriteStringInternal (text, true);
		}

		public void WriteStringInternal (string text, bool entitize)
		{
			if (text == null)
				text = String.Empty;

			if (text != String.Empty) 
			{
				CheckState ();

				if (entitize)
				{
					text = text.Replace ("&", "&amp;");
					text = text.Replace ("<", "&lt;");
					text = text.Replace (">", "&gt;");
					
					if (openAttribute) 
					{
						if (quoteChar == '"')
							text = text.Replace ("\"", "&quot;");
						else
							text = text.Replace ("'", "&apos;");
					}
				}

				if (!openAttribute)
					CloseStartElement ();

				if (!openXmlLang && !openXmlSpace)
					w.Write (text);
				else 
				{
					if (openXmlLang)
						xmlLang = text;
					else 
					{
						switch (text) 
						{
							case "default":
								xmlSpace = XmlSpace.Default;
								break;
							case "preserve":
								xmlSpace = XmlSpace.Preserve;
								break;
							default:
								throw new ArgumentException ("'{0}' is an invalid xml:space value.");
						}
					}
				}
			}

			IndentingOverriden = true;
		}

		[MonoTODO]
		public override void WriteSurrogateCharEntity (char lowChar, char highChar)
		{
			throw new NotImplementedException ();
		}

		public override void WriteWhitespace (string ws)
		{
			foreach (char c in ws) {
				if ((c != ' ') && (c != '\t') && (c != '\r') && (c != '\n'))
					throw new ArgumentException ();
			}

			w.Write (ws);
		}

		#endregion
	}
}