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);
300 public override void WriteDocType (string name, string pubid, string sysid, string subset)
302 if (name == null || name.Trim ().Length == 0)
303 throw new ArgumentException ("Invalid DOCTYPE name", "name");
305 w.Write ("<!DOCTYPE ");
308 w.Write (String.Format (" PUBLIC {0}{1}{0} {0}{2}{0}", quoteChar, pubid, sysid));
309 } else if (sysid != null) {
310 w.Write (String.Format (" SYSTEM {0}{1}{0}", quoteChar, sysid));
314 w.Write ("[" + subset + "]");
319 public override void WriteEndAttribute ()
322 throw new InvalidOperationException("Token EndAttribute in state Start would result in an invalid XML document.");
329 ((XmlTextWriterOpenElement)openElements.Peek()).XmlLang = xmlLang;
334 w.Write (xmlSpace.ToString ().ToLower ());
335 openXmlSpace = false;
336 ((XmlTextWriterOpenElement)openElements.Peek()).XmlSpace = xmlSpace;
339 w.Write ("{0}", quoteChar);
341 openAttribute = false;
344 public override void WriteEndDocument ()
346 CloseOpenAttributeAndElements ();
348 if ((ws == WriteState.Start) || (ws == WriteState.Prolog))
349 throw new ArgumentException ("This document does not have a root element.");
351 ws = WriteState.Start;
354 public override void WriteEndElement ()
356 WriteEndElementInternal (false);
359 private void WriteEndElementInternal (bool fullEndElement)
361 if (openElements.Count == 0)
362 throw new InvalidOperationException("There was no XML start tag open.");
367 if (openStartElement) {
369 WriteEndAttribute ();
371 w.Write ("></{0}>", ((XmlTextWriterOpenElement)openElements.Peek ()).Name);
376 openStartElement = false;
378 w.Write ("{0}</{1}>", indentFormatting, openElements.Pop ());
381 namespaceManager.PopScope();
385 public override void WriteEntityRef (string name)
387 throw new NotImplementedException ();
390 public override void WriteFullEndElement ()
392 WriteEndElementInternal (true);
396 public override void WriteName (string name)
398 throw new NotImplementedException ();
402 public override void WriteNmToken (string name)
404 throw new NotImplementedException ();
407 public override void WriteProcessingInstruction (string name, string text)
409 if ((name == null) || (name == string.Empty) || (name.IndexOf("?>") > 0) || (text.IndexOf("?>") > 0)) {
410 throw new ArgumentException ();
414 CloseStartElement ();
416 w.Write ("{0}<?{1} {2}?>", indentFormatting, name, text);
420 public override void WriteQualifiedName (string localName, string ns)
422 if (localName == null || localName == String.Empty)
423 throw new ArgumentException ();
426 w.Write ("{0}:{1}", ns, localName);
429 public override void WriteRaw (string data)
431 WriteStringInternal (data, false);
435 public override void WriteRaw (char[] buffer, int index, int count)
437 throw new NotImplementedException ();
440 public override void WriteStartAttribute (string prefix, string localName, string ns)
442 if ((prefix == "xml") && (localName == "lang"))
445 if ((prefix == "xml") && (localName == "space"))
448 if ((prefix == "xmlns") && (localName == "xmlns"))
449 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.");
453 if (ws == WriteState.Content)
454 throw new InvalidOperationException ("Token StartAttribute in state " + WriteState + " would result in an invalid XML document.");
457 prefix = String.Empty;
462 string formatPrefix = "";
463 string formatSpace = "";
465 if (ns != String.Empty)
467 string existingPrefix = namespaceManager.LookupPrefix (ns);
469 if (prefix == String.Empty)
470 prefix = existingPrefix;
473 if (prefix != String.Empty)
475 formatPrefix = prefix + ":";
478 if (openStartElement || attributeWrittenForElement)
481 w.Write ("{0}{1}{2}={3}", formatSpace, formatPrefix, localName, quoteChar);
483 openAttribute = true;
484 attributeWrittenForElement = true;
485 ws = WriteState.Attribute;
488 public override void WriteStartDocument ()
490 WriteStartDocument ("");
493 public override void WriteStartDocument (bool standalone)
495 string standaloneFormatting;
497 if (standalone == true)
498 standaloneFormatting = String.Format (" standalone={0}yes{0}", quoteChar);
500 standaloneFormatting = String.Format (" standalone={0}no{0}", quoteChar);
502 WriteStartDocument (standaloneFormatting);
505 private void WriteStartDocument (string standaloneFormatting)
507 if (documentStarted == true)
508 throw new InvalidOperationException("WriteStartDocument should be the first call.");
512 string encodingFormatting = "";
515 encodingFormatting = String.Format (" encoding={0}{1}{0}", quoteChar, w.Encoding.HeaderName);
517 w.Write("<?xml version={0}1.0{0}{1}{2}?>", quoteChar, encodingFormatting, standaloneFormatting);
518 ws = WriteState.Prolog;
521 public override void WriteStartElement (string prefix, string localName, string ns)
523 if (!Namespaces && (((prefix != null) && (prefix != String.Empty))
524 || ((ns != null) && (ns != String.Empty))))
525 throw new ArgumentException ("Cannot set the namespace if Namespaces is 'false'.");
527 WriteStartElementInternal (prefix, localName, ns);
530 private void WriteStartElementInternal (string prefix, string localName, string ns)
533 prefix = String.Empty;
535 if ((prefix != String.Empty) && ((ns == null) || (ns == String.Empty)))
536 throw new ArgumentException ("Cannot use a prefix with an empty namespace.");
539 CloseStartElement ();
541 string formatXmlns = "";
542 string formatPrefix = "";
546 if (ns != String.Empty)
548 string existingPrefix = namespaceManager.LookupPrefix (ns);
550 if (prefix == String.Empty)
551 prefix = existingPrefix;
553 if (prefix != existingPrefix)
554 formatXmlns = String.Format (" xmlns:{0}={1}{2}{1}", prefix, quoteChar, ns);
555 else if (existingPrefix == String.Empty)
556 formatXmlns = String.Format (" xmlns={0}{1}{0}", quoteChar, ns);
558 else if ((prefix == String.Empty) && (namespaceManager.LookupNamespace(prefix) != String.Empty)) {
559 formatXmlns = String.Format (" xmlns={0}{0}", quoteChar);
562 if (prefix != String.Empty) {
563 formatPrefix = prefix + ":";
567 w.Write ("{0}<{1}{2}{3}", indentFormatting, formatPrefix, localName, formatXmlns);
570 openElements.Push (new XmlTextWriterOpenElement (formatPrefix + localName));
571 ws = WriteState.Element;
572 openStartElement = true;
574 namespaceManager.PushScope ();
577 namespaceManager.AddNamespace (prefix, ns);
582 public override void WriteString (string text)
584 if (ws == WriteState.Prolog)
585 throw new InvalidOperationException ("Token content in state Prolog would result in an invalid XML document.");
587 WriteStringInternal (text, true);
590 private void WriteStringInternal (string text, bool entitize)
595 if (text != String.Empty)
601 text = text.Replace ("&", "&");
602 text = text.Replace ("<", "<");
603 text = text.Replace (">", ">");
607 if (quoteChar == '"')
608 text = text.Replace ("\"", """);
610 text = text.Replace ("'", "'");
616 IndentingOverriden = true;
617 CloseStartElement ();
619 if (!openXmlLang && !openXmlSpace)
630 xmlSpace = XmlSpace.Default;
633 xmlSpace = XmlSpace.Preserve;
636 throw new ArgumentException ("'{0}' is an invalid xml:space value.");
644 public override void WriteSurrogateCharEntity (char lowChar, char highChar)
646 throw new NotImplementedException ();
649 public override void WriteWhitespace (string ws)
651 foreach (char c in ws) {
652 if ((c != ' ') && (c != '\t') && (c != '\r') && (c != '\n'))
653 throw new ArgumentException ();