2 // System.Xml.XmlTextWriter
5 // Kral Ferch <kral_ferch@hotmail.com>
11 using System.Collections;
17 public class XmlTextWriter : XmlWriter
22 bool nullEncoding = false;
23 bool openWriter = true;
24 bool openStartElement = false;
25 bool openStartAttribute = false;
26 bool documentStarted = false;
27 bool namespaces = true;
28 bool openAttribute = false;
29 bool attributeWrittenForElement = false;
30 Stack openElements = new Stack ();
31 Formatting formatting = Formatting.None;
33 char indentChar = ' ';
34 string indentChars = " ";
35 char quoteChar = '\"';
37 string indentFormatting;
38 Stream baseStream = null;
39 string xmlLang = null;
40 XmlSpace xmlSpace = XmlSpace.None;
41 bool openXmlLang = false;
42 bool openXmlSpace = false;
48 public XmlTextWriter (TextWriter w) : base ()
51 nullEncoding = (w.Encoding == null);
54 baseStream = ((StreamWriter)w).BaseStream;
59 public XmlTextWriter (Stream w, Encoding encoding) : base ()
61 if (encoding == null) {
63 encoding = new UTF8Encoding ();
66 this.w = new StreamWriter(w, encoding);
70 public XmlTextWriter (string filename, Encoding encoding) :
71 this (new FileStream (filename, FileMode.Create, FileAccess.Write, FileShare.None), encoding)
79 public Stream BaseStream {
80 get { return baseStream; }
84 public Formatting Formatting {
85 get { return formatting; }
86 set { formatting = value; }
89 private bool IndentingOverriden
92 if (openElements.Count == 0)
95 return (((XmlTextWriterOpenElement)openElements.Peek()).IndentingOverriden);
98 if (openElements.Count > 0)
99 ((XmlTextWriterOpenElement)openElements.Peek()).IndentingOverriden = value;
103 public int Indentation {
104 get { return indentation; }
107 UpdateIndentChars ();
111 public char IndentChar {
112 get { return indentChar; }
115 UpdateIndentChars ();
119 public bool Namespaces {
120 get { return namespaces; }
122 if (ws != WriteState.Start)
123 throw new InvalidOperationException ("NotInWriteState.");
129 public char QuoteChar {
130 get { return quoteChar; }
132 if ((value != '\'') && (value != '\"'))
133 throw new ArgumentException ("This is an invalid XML attribute quote character. Valid attribute quote characters are ' and \".");
139 public override WriteState WriteState {
143 public override string XmlLang {
145 string xmlLang = null;
148 for (i = 0; i < openElements.Count; i++)
150 xmlLang = ((XmlTextWriterOpenElement)openElements.ToArray().GetValue(i)).XmlLang;
159 public override XmlSpace XmlSpace {
161 XmlSpace xmlSpace = XmlSpace.None;
164 for (i = 0; i < openElements.Count; i++)
166 xmlSpace = ((XmlTextWriterOpenElement)openElements.ToArray().GetValue(i)).XmlSpace;
167 if (xmlSpace != XmlSpace.None)
179 private void CheckState ()
182 throw new InvalidOperationException ("The Writer is closed.");
184 if ((documentStarted == true) && (formatting == Formatting.Indented) && (!IndentingOverriden)) {
185 indentFormatting = "\r\n";
186 if (indentLevel > 0) {
187 for (int i = 0; i < indentLevel; i++)
188 indentFormatting += indentChars;
192 indentFormatting = "";
194 documentStarted = true;
197 public override void Close ()
199 CloseOpenAttributeAndElements ();
202 ws = WriteState.Closed;
206 private void CloseOpenAttributeAndElements ()
209 WriteEndAttribute ();
211 while (openElements.Count > 0) {
216 private void CloseStartElement ()
218 if (openStartElement) {
220 ws = WriteState.Content;
221 openStartElement = false;
222 attributeWrittenForElement = false;
226 public override void Flush ()
231 public override string LookupPrefix (string ns)
233 string prefix = namespaceManager.LookupPrefix (ns);
235 if (prefix == String.Empty)
241 private void UpdateIndentChars ()
244 for (int i = 0; i < indentation; i++)
245 indentChars += indentChar;
248 public override void WriteBase64 (byte[] buffer, int index, int count)
250 w.Write (Convert.ToBase64String (buffer, index, count));
254 public override void WriteBinHex (byte[] buffer, int index, int count)
256 throw new NotImplementedException ();
259 public override void WriteCData (string text)
261 if (text.IndexOf("]]>") > 0)
262 throw new ArgumentException ();
265 CloseStartElement ();
267 w.Write("<![CDATA[{0}]]>", text);
270 public override void WriteCharEntity (char ch)
272 Int16 intCh = (Int16)ch;
274 // Make sure the character is not in the surrogate pair
275 // character range, 0xd800- 0xdfff
276 if ((intCh >= -10240) && (intCh <= -8193))
277 throw new ArgumentException ("Surrogate Pair is invalid.");
279 w.Write("&#x{0:X};", intCh);
283 public override void WriteChars (char[] buffer, int index, int count)
285 throw new NotImplementedException ();
288 public override void WriteComment (string text)
290 if ((text.EndsWith("-")) || (text.IndexOf("-->") > 0)) {
291 throw new ArgumentException ();
295 CloseStartElement ();
297 w.Write ("<!--{0}-->", text);
301 public override void WriteDocType (string name, string pubid, string sysid, string subset)
303 throw new NotImplementedException ();
306 public override void WriteEndAttribute ()
309 throw new InvalidOperationException("Token EndAttribute in state Start would result in an invalid XML document.");
316 ((XmlTextWriterOpenElement)openElements.Peek()).XmlLang = xmlLang;
321 w.Write (xmlSpace.ToString ().ToLower ());
322 openXmlSpace = false;
323 ((XmlTextWriterOpenElement)openElements.Peek()).XmlSpace = xmlSpace;
326 w.Write ("{0}", quoteChar);
328 openAttribute = false;
331 public override void WriteEndDocument ()
333 CloseOpenAttributeAndElements ();
335 if ((ws == WriteState.Start) || (ws == WriteState.Prolog))
336 throw new ArgumentException ("This document does not have a root element.");
338 ws = WriteState.Start;
341 public override void WriteEndElement ()
343 WriteEndElementInternal (false);
346 private void WriteEndElementInternal (bool fullEndElement)
348 if (openElements.Count == 0)
349 throw new InvalidOperationException("There was no XML start tag open.");
354 if (openStartElement) {
356 WriteEndAttribute ();
358 w.Write ("></{0}>", ((XmlTextWriterOpenElement)openElements.Peek ()).Name);
363 openStartElement = false;
365 w.Write ("{0}</{1}>", indentFormatting, openElements.Pop ());
368 namespaceManager.PopScope();
372 public override void WriteEntityRef (string name)
374 throw new NotImplementedException ();
377 public override void WriteFullEndElement ()
379 WriteEndElementInternal (true);
383 public override void WriteName (string name)
385 throw new NotImplementedException ();
389 public override void WriteNmToken (string name)
391 throw new NotImplementedException ();
394 public override void WriteProcessingInstruction (string name, string text)
396 if ((name == null) || (name == string.Empty) || (name.IndexOf("?>") > 0) || (text.IndexOf("?>") > 0)) {
397 throw new ArgumentException ();
401 CloseStartElement ();
403 w.Write ("{0}<?{1} {2}?>", indentFormatting, name, text);
407 public override void WriteQualifiedName (string localName, string ns)
409 if (localName == null || localName == String.Empty)
410 throw new ArgumentException ();
413 w.Write ("{0}:{1}", ns, localName);
416 public override void WriteRaw (string data)
418 WriteStringInternal (data, false);
422 public override void WriteRaw (char[] buffer, int index, int count)
424 throw new NotImplementedException ();
427 public override void WriteStartAttribute (string prefix, string localName, string ns)
429 if ((prefix == "xml") && (localName == "lang"))
432 if ((prefix == "xml") && (localName == "space"))
435 if ((prefix == "xmlns") && (localName == "xmlns"))
436 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.");
440 if (ws == WriteState.Content)
441 throw new InvalidOperationException ("Token StartAttribute in state " + WriteState + " would result in an invalid XML document.");
444 prefix = String.Empty;
449 string formatPrefix = "";
450 string formatSpace = "";
452 if (ns != String.Empty)
454 string existingPrefix = namespaceManager.LookupPrefix (ns);
456 if (prefix == String.Empty)
457 prefix = existingPrefix;
460 if (prefix != String.Empty)
462 formatPrefix = prefix + ":";
465 if (openStartElement || attributeWrittenForElement)
468 w.Write ("{0}{1}{2}={3}", formatSpace, formatPrefix, localName, quoteChar);
470 openAttribute = true;
471 attributeWrittenForElement = true;
472 ws = WriteState.Attribute;
475 public override void WriteStartDocument ()
477 WriteStartDocument ("");
480 public override void WriteStartDocument (bool standalone)
482 string standaloneFormatting;
484 if (standalone == true)
485 standaloneFormatting = String.Format (" standalone={0}yes{0}", quoteChar);
487 standaloneFormatting = String.Format (" standalone={0}no{0}", quoteChar);
489 WriteStartDocument (standaloneFormatting);
492 private void WriteStartDocument (string standaloneFormatting)
494 if (documentStarted == true)
495 throw new InvalidOperationException("WriteStartDocument should be the first call.");
499 string encodingFormatting = "";
502 encodingFormatting = String.Format (" encoding={0}{1}{0}", quoteChar, w.Encoding.HeaderName);
504 w.Write("<?xml version={0}1.0{0}{1}{2}?>", quoteChar, encodingFormatting, standaloneFormatting);
505 ws = WriteState.Prolog;
508 public override void WriteStartElement (string prefix, string localName, string ns)
510 if (!Namespaces && (((prefix != null) && (prefix != String.Empty))
511 || ((ns != null) && (ns != String.Empty))))
512 throw new ArgumentException ("Cannot set the namespace if Namespaces is 'false'.");
514 WriteStartElementInternal (prefix, localName, ns);
517 private void WriteStartElementInternal (string prefix, string localName, string ns)
520 prefix = String.Empty;
522 if ((prefix != String.Empty) && ((ns == null) || (ns == String.Empty)))
523 throw new ArgumentException ("Cannot use a prefix with an empty namespace.");
526 CloseStartElement ();
528 string formatXmlns = "";
529 string formatPrefix = "";
533 if (ns != String.Empty)
535 string existingPrefix = namespaceManager.LookupPrefix (ns);
537 if (prefix == String.Empty)
538 prefix = existingPrefix;
540 if (prefix != existingPrefix)
541 formatXmlns = String.Format (" xmlns:{0}={1}{2}{1}", prefix, quoteChar, ns);
542 else if (existingPrefix == String.Empty)
543 formatXmlns = String.Format (" xmlns={0}{1}{0}", quoteChar, ns);
545 else if ((prefix == String.Empty) && (namespaceManager.LookupNamespace(prefix) != String.Empty)) {
546 formatXmlns = String.Format (" xmlns={0}{0}", quoteChar);
549 if (prefix != String.Empty) {
550 formatPrefix = prefix + ":";
554 w.Write ("{0}<{1}{2}{3}", indentFormatting, formatPrefix, localName, formatXmlns);
557 openElements.Push (new XmlTextWriterOpenElement (formatPrefix + localName));
558 ws = WriteState.Element;
559 openStartElement = true;
561 namespaceManager.PushScope ();
564 namespaceManager.AddNamespace (prefix, ns);
569 public override void WriteString (string text)
571 if (ws == WriteState.Prolog)
572 throw new InvalidOperationException ("Token content in state Prolog would result in an invalid XML document.");
574 WriteStringInternal (text, true);
577 private void WriteStringInternal (string text, bool entitize)
582 if (text != String.Empty)
588 text = text.Replace ("&", "&");
589 text = text.Replace ("<", "<");
590 text = text.Replace (">", ">");
594 if (quoteChar == '"')
595 text = text.Replace ("\"", """);
597 text = text.Replace ("'", "'");
603 IndentingOverriden = true;
604 CloseStartElement ();
606 if (!openXmlLang && !openXmlSpace)
617 xmlSpace = XmlSpace.Default;
620 xmlSpace = XmlSpace.Preserve;
623 throw new ArgumentException ("'{0}' is an invalid xml:space value.");
631 public override void WriteSurrogateCharEntity (char lowChar, char highChar)
633 throw new NotImplementedException ();
636 public override void WriteWhitespace (string ws)
638 foreach (char c in ws) {
639 if ((c != ' ') && (c != '\t') && (c != '\r') && (c != '\n'))
640 throw new ArgumentException ();