2 // System.Xml.XmlTextWriter
5 // Kral Ferch <kral_ferch@hotmail.com>
11 using System.Collections;
17 public class XmlTextWriter : XmlWriter
21 protected TextWriter w;
22 protected bool nullEncoding = false;
23 protected bool openWriter = true;
24 protected bool openStartElement = false;
25 protected bool openStartAttribute = false;
26 protected bool documentStarted = false;
27 protected bool namespaces = true;
28 protected bool openAttribute = false;
29 protected bool attributeWrittenForElement = false;
30 protected Stack openElements = new Stack ();
31 protected Formatting formatting = Formatting.None;
32 protected int indentation = 2;
33 protected char indentChar = ' ';
34 protected string indentChars = " ";
35 protected char quoteChar = '\"';
36 protected int indentLevel = 0;
37 protected string indentFormatting;
38 protected Stream baseStream = null;
39 protected string xmlLang = null;
40 protected XmlSpace xmlSpace = XmlSpace.None;
41 protected bool openXmlLang = false;
42 protected bool openXmlSpace = false;
48 public XmlTextWriter (TextWriter w) : base ()
53 baseStream = ((StreamWriter)w).BaseStream;
58 public XmlTextWriter (Stream w, Encoding encoding) : base ()
60 if (encoding == null) {
62 encoding = new UTF8Encoding ();
65 this.w = new StreamWriter(w, encoding);
69 public XmlTextWriter (string filename, Encoding encoding) : base ()
71 this.w = new StreamWriter(filename, false, encoding);
72 baseStream = ((StreamWriter)w).BaseStream;
79 public Stream BaseStream {
80 get { return baseStream; }
84 public Formatting Formatting {
85 get { return formatting; }
86 set { formatting = value; }
89 public 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.");
185 if ((documentStarted == true) && (formatting == Formatting.Indented) && (!IndentingOverriden)) {
186 indentFormatting = "\r\n";
187 if (indentLevel > 0) {
188 for (int i = 0; i < indentLevel; i++)
189 indentFormatting += indentChars;
193 indentFormatting = "";
195 documentStarted = true;
198 public override void Close ()
200 while (openElements.Count > 0) {
205 ws = WriteState.Closed;
209 private void CloseStartElement ()
211 if (openStartElement)
214 ws = WriteState.Content;
215 openStartElement = false;
216 attributeWrittenForElement = false;
220 public override void Flush ()
226 public override string LookupPrefix (string ns)
228 throw new NotImplementedException ();
231 private void UpdateIndentChars ()
234 for (int i = 0; i < indentation; i++)
235 indentChars += indentChar;
239 public override void WriteBase64 (byte[] buffer, int index, int count)
241 throw new NotImplementedException ();
245 public override void WriteBinHex (byte[] buffer, int index, int count)
247 throw new NotImplementedException ();
250 public override void WriteCData (string text)
252 if (text.IndexOf("]]>") > 0)
254 throw new ArgumentException ();
258 CloseStartElement ();
260 w.Write("<![CDATA[{0}]]>", text);
264 public override void WriteCharEntity (char ch)
266 throw new NotImplementedException ();
270 public override void WriteChars (char[] buffer, int index, int count)
272 throw new NotImplementedException ();
275 public override void WriteComment (string text)
277 if ((text.EndsWith("-")) || (text.IndexOf("-->") > 0)) {
278 throw new ArgumentException ();
282 CloseStartElement ();
284 w.Write ("<!--{0}-->", text);
288 public override void WriteDocType (string name, string pubid, string sysid, string subset)
290 throw new NotImplementedException ();
293 public override void WriteEndAttribute ()
296 throw new InvalidOperationException("Token EndAttribute in state Start would result in an invalid XML document.");
303 ((XmlTextWriterOpenElement)openElements.Peek()).XmlLang = xmlLang;
308 w.Write (xmlSpace.ToString ().ToLower ());
309 openXmlSpace = false;
310 ((XmlTextWriterOpenElement)openElements.Peek()).XmlSpace = xmlSpace;
313 w.Write ("{0}", quoteChar);
315 openAttribute = false;
319 public override void WriteEndDocument ()
321 throw new NotImplementedException ();
324 public override void WriteEndElement ()
326 if (openElements.Count == 0)
327 throw new InvalidOperationException("There was no XML start tag open.");
333 if (openStartElement) {
336 openStartElement = false;
339 w.Write ("{0}</{1}>", indentFormatting, openElements.Pop ());
340 namespaceManager.PopScope();
345 public override void WriteEntityRef (string name)
347 throw new NotImplementedException ();
351 public override void WriteFullEndElement ()
353 throw new NotImplementedException ();
357 public override void WriteName (string name)
359 throw new NotImplementedException ();
363 public override void WriteNmToken (string name)
365 throw new NotImplementedException ();
368 public override void WriteProcessingInstruction (string name, string text)
370 if ((name == null) || (name == string.Empty) || (name.IndexOf("?>") > 0) || (text.IndexOf("?>") > 0)) {
371 throw new ArgumentException ();
375 CloseStartElement ();
377 w.Write ("{0}<?{1} {2}?>", indentFormatting, name, text);
381 public override void WriteQualifiedName (string localName, string ns)
383 throw new NotImplementedException ();
387 public override void WriteRaw (string data)
389 throw new NotImplementedException ();
393 public override void WriteRaw (char[] buffer, int index, int count)
395 throw new NotImplementedException ();
398 [MonoTODO("haven't tested namespaces on attributes code yet.")]
399 public override void WriteStartAttribute (string prefix, string localName, string ns)
401 if ((prefix == "xml") && (localName == "lang"))
404 if ((prefix == "xml") && (localName == "space"))
407 if ((prefix == "xmlns") && (localName == "xmlns"))
408 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.");
412 if (ws == WriteState.Content)
413 throw new InvalidOperationException ("Token StartAttribute in state " + WriteState + " would result in an invalid XML document.");
416 prefix = String.Empty;
421 string formatPrefix = "";
422 string formatSpace = "";
424 if (ns != String.Empty)
426 string existingPrefix = namespaceManager.LookupPrefix (ns);
428 if (prefix == String.Empty)
429 prefix = existingPrefix;
432 if (prefix != String.Empty)
434 formatPrefix = prefix + ":";
437 if (openStartElement || attributeWrittenForElement)
440 w.Write ("{0}{1}{2}={3}", formatSpace, formatPrefix, localName, quoteChar);
442 openAttribute = true;
443 attributeWrittenForElement = true;
444 ws = WriteState.Attribute;
447 public override void WriteStartDocument ()
449 WriteStartDocument ("");
452 public override void WriteStartDocument (bool standalone)
454 string standaloneFormatting;
456 if (standalone == true)
457 standaloneFormatting = String.Format (" standalone={0}yes{0}", quoteChar);
459 standaloneFormatting = String.Format (" standalone={0}no{0}", quoteChar);
461 WriteStartDocument (standaloneFormatting);
464 private void WriteStartDocument (string standaloneFormatting)
466 if (documentStarted == true)
467 throw new InvalidOperationException("WriteStartDocument should be the first call.");
471 string encodingFormatting = "";
474 encodingFormatting = String.Format (" encoding={0}{1}{0}", quoteChar, w.Encoding.HeaderName);
476 w.Write("<?xml version={0}1.0{0}{1}{2}?>", quoteChar, encodingFormatting, standaloneFormatting);
477 ws = WriteState.Prolog;
480 public override void WriteStartElement (string prefix, string localName, string ns)
482 if (!Namespaces && (((prefix != null) && (prefix != String.Empty))
483 || ((ns != null) && (ns != String.Empty))))
484 throw new ArgumentException ("Cannot set the namespace if Namespaces is 'false'.");
486 WriteStartElementInternal (prefix, localName, ns);
489 protected override void WriteStartElementInternal (string prefix, string localName, string ns)
492 prefix = String.Empty;
497 if ((prefix != String.Empty) && ((ns == null) || (ns == String.Empty)))
498 throw new ArgumentException ("Cannot use a prefix with an empty namespace.");
501 CloseStartElement ();
503 string formatXmlns = "";
504 string formatPrefix = "";
506 if (ns != String.Empty)
508 string existingPrefix = namespaceManager.LookupPrefix (ns);
510 if (prefix == String.Empty)
511 prefix = existingPrefix;
513 if (prefix != existingPrefix)
514 formatXmlns = String.Format (" xmlns:{0}={1}{2}{1}", prefix, quoteChar, ns);
515 else if (existingPrefix == String.Empty)
516 formatXmlns = String.Format (" xmlns={0}{1}{0}", quoteChar, ns);
518 else if ((prefix == String.Empty) && (namespaceManager.LookupNamespace(prefix) != String.Empty)) {
519 formatXmlns = String.Format (" xmlns={0}{0}", quoteChar);
522 if (prefix != String.Empty) {
523 formatPrefix = prefix + ":";
526 w.Write ("{0}<{1}{2}{3}", indentFormatting, formatPrefix, localName, formatXmlns);
528 openElements.Push (new XmlTextWriterOpenElement (formatPrefix + localName));
529 ws = WriteState.Element;
530 openStartElement = true;
532 namespaceManager.PushScope ();
533 namespaceManager.AddNamespace (prefix, ns);
538 public override void WriteString (string text)
540 if (ws == WriteState.Prolog)
541 throw new InvalidOperationException ("Token content in state Prolog would result in an invalid XML document.");
546 if (text != String.Empty) {
549 text = text.Replace ("&", "&");
550 text = text.Replace ("<", "<");
551 text = text.Replace (">", ">");
554 if (quoteChar == '"')
555 text = text.Replace ("\"", """);
557 text = text.Replace ("'", "'");
561 CloseStartElement ();
563 if (!openXmlLang && !openXmlSpace)
571 xmlSpace = XmlSpace.Default;
574 xmlSpace = XmlSpace.Preserve;
577 throw new ArgumentException ("'{0}' is an invalid xml:space value.");
583 IndentingOverriden = true;
587 public override void WriteSurrogateCharEntity (char lowChar, char highChar)
589 throw new NotImplementedException ();
592 public override void WriteWhitespace (string ws)
594 foreach (char c in ws) {
595 if ((c != ' ') && (c != '\t') && (c != '\r') && (c != '\n'))
596 throw new ArgumentException ();