a987dd350737b5ed2f2493ba93632956eb22ec23
[mono.git] / mcs / class / System.XML / System.Xml / XmlWriter.cs
1 //
2 // System.Xml.XmlWriter
3 //
4 // Authors:
5 //   Kral Ferch <kral_ferch@hotmail.com>
6 //   Atsushi Enomoto <ginga@kit.hi-ho.ne.jp>
7 //
8 // (C) 2002 Kral Ferch
9 // (C) 2002-2003 Atsushi Enomoto
10 //
11
12 //
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
20 // 
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 // 
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 //
32
33 using System;
34 using System.IO;
35 using System.Text;
36 #if NET_2_0
37 using System.Xml.XPath;
38 #endif
39
40 namespace System.Xml
41 {
42 #if NET_2_0
43         public abstract class XmlWriter : IDisposable
44 #else
45         public abstract class XmlWriter
46 #endif
47         {
48 #if NET_2_0
49                 XmlWriterSettings settings;
50 #endif
51
52                 #region Constructors
53
54                 protected XmlWriter () { }
55
56                 #endregion
57
58                 #region Properties
59
60 #if NET_2_0
61                 public virtual XmlWriterSettings Settings {
62                         get {
63                                 if (settings == null)
64                                         settings = new XmlWriterSettings ();
65                                 return settings;
66                         }
67                 }
68 #endif
69
70                 public abstract WriteState WriteState { get; }
71                 
72
73 #if NET_2_0
74                 public virtual string XmlLang {
75                         get { return null; }
76                 }
77
78                 public virtual XmlSpace XmlSpace {
79                         get { return XmlSpace.None; }
80                 }
81 #else
82                 public abstract string XmlLang { get; }
83
84                 public abstract XmlSpace XmlSpace { get; }
85 #endif
86
87                 #endregion
88
89                 #region Methods
90
91                 public abstract void Close ();
92
93 #if NET_2_0
94                 public static XmlWriter Create (Stream stream)
95                 {
96                         return Create (stream, null);
97                 }
98
99                 public static XmlWriter Create (string file)
100                 {
101                         return Create (file, null);
102                 }
103
104                 public static XmlWriter Create (TextWriter writer)
105                 {
106                         return Create (writer, null);
107                 }
108
109                 public static XmlWriter Create (XmlWriter writer)
110                 {
111                         return Create (writer, null);
112                 }
113
114                 public static XmlWriter Create (StringBuilder builder)
115                 {
116                         return Create (builder, null);
117                 }
118
119                 [MonoTODO ("NewLineHandling/OutputMethod")]
120                 public static XmlWriter Create (Stream stream, XmlWriterSettings settings)
121                 {
122                         // FIXME: this might result in encoding null reference
123                         Encoding enc = settings != null ? settings.Encoding : Encoding.UTF8;
124                         return Create (new StreamWriter (stream, enc), settings);
125                 }
126
127                 [MonoTODO ("NewLineHandling/OutputMethod")]
128                 public static XmlWriter Create (string file, XmlWriterSettings settings)
129                 {
130                         // FIXME: this might result in encoding null reference
131                         Encoding enc = settings != null ? settings.Encoding : Encoding.UTF8;
132                         return Create (new StreamWriter (file, false, enc), settings);
133                 }
134
135                 [MonoTODO ("NewLineHandling/OutputMethod")]
136                 public static XmlWriter Create (StringBuilder builder, XmlWriterSettings settings)
137                 {
138                         return Create (new StringWriter (builder), null);
139                 }
140
141                 [MonoTODO ("NewLineHandling/OutputMethod")]
142                 public static XmlWriter Create (TextWriter writer, XmlWriterSettings settings)
143                 {
144                         return CreateTextWriter (writer, settings);
145                 }
146
147                 [MonoTODO ("NewLineHandling/OutputMethod")]
148                 public static XmlWriter Create (XmlWriter writer, XmlWriterSettings settings)
149                 {
150                         if (settings == null)
151                                 settings = new XmlWriterSettings ();
152                         writer.settings = settings;
153                         return writer;
154                 }
155
156                 private static XmlWriter CreateTextWriter (TextWriter writer, XmlWriterSettings settings)
157                 {
158                         if (settings == null)
159                                 settings = new XmlWriterSettings ();
160                         XmlTextWriter xtw = new XmlTextWriter (writer);
161                         // Indent, IndentChars
162                         if (settings.Indent) {
163                                 xtw.Formatting = Formatting.Indented;
164                                 xtw.IndentChars = settings.IndentChars;
165                                 xtw.NewLineOnAttributes = settings.NewLineOnAttributes;
166                         }
167                         // NewLineChars
168                         xtw.NewLineChars = settings.NewLineChars;
169                         // CloseOutput
170                         xtw.CloseOutput = settings.CloseOutput;
171                         // ConformanceLevel
172                         xtw.ConformanceLevel = settings.ConformanceLevel;
173                         // OmitXmlDeclaration
174                         xtw.OmitXmlDeclaration = settings.OmitXmlDeclaration;
175                         // CheckCharacters
176                         xtw.CheckCharacters = settings.CheckCharacters;
177                         return Create (xtw, settings);
178                 }
179
180                 public virtual void Dispose (bool disposing)
181                 {
182                         Close ();
183                 }
184
185                 void IDisposable.Dispose ()
186                 {
187                         Dispose (false);
188                 }
189 #endif
190
191                 public abstract void Flush ();
192
193                 public abstract string LookupPrefix (string ns);
194
195                 private void WriteAttribute (XmlReader reader, bool defattr)
196                 {
197                         if (!defattr && reader.IsDefault)
198                                 return;
199
200                         WriteStartAttribute (reader.Prefix, reader.LocalName, reader.NamespaceURI);
201                         while (reader.ReadAttributeValue ()) {
202                                 switch (reader.NodeType) {
203                                 case XmlNodeType.Text:
204                                         WriteString (reader.Value);
205                                         break;
206                                 case XmlNodeType.EntityReference:
207                                         WriteEntityRef (reader.Name);
208                                         break;
209                                 }
210                         }
211                         WriteEndAttribute ();
212                 }
213
214                 public virtual void WriteAttributes (XmlReader reader, bool defattr)
215                 {
216                         if(reader == null)
217                                 throw new ArgumentException("null XmlReader specified.", "reader");
218
219                         switch (reader.NodeType) {
220                         case XmlNodeType.XmlDeclaration:
221                                 WriteAttributeString ("version", reader ["version"]);
222                                 if (reader ["encoding"] != null)
223                                         WriteAttributeString ("encoding", reader ["encoding"]);
224                                 if (reader ["standalone"] != null)
225                                         WriteAttributeString ("standalone", reader ["standalone"]);
226                                 break;
227                         case XmlNodeType.Element:
228                                 if (reader.MoveToFirstAttribute ())
229                                         goto case XmlNodeType.Attribute;
230                                 break;
231                         case XmlNodeType.Attribute:
232                                 do {
233                                         WriteAttribute (reader, defattr);
234                                 } while (reader.MoveToNextAttribute ());
235                                 reader.MoveToElement ();
236                                 break;
237                         default:
238                                 throw new XmlException("NodeType is not one of Element, Attribute, nor XmlDeclaration.");
239                         }
240                 }
241
242                 public void WriteAttributeString (string localName, string value)
243                 {
244                         WriteAttributeString ("", localName, null, value);
245                 }
246
247                 public void WriteAttributeString (string localName, string ns, string value)
248                 {
249                         WriteAttributeString ("", localName, ns, value);
250                 }
251
252                 public void WriteAttributeString (string prefix, string localName, string ns, string value)
253                 {
254                         // In MS.NET (1.0), this check is done *here*, not at WriteStartAttribute.
255                         // (XmlTextWriter.WriteStartAttribute("xmlns", "anyname", null) throws an exception.
256
257 #if NET_1_0
258                         if ((prefix == "xmlns" || (prefix == "" && localName == "xmlns")) && ns == null)
259                                 ns = "http://www.w3.org/2000/xmlns/";
260 #endif
261
262                         WriteStartAttribute (prefix, localName, ns);
263                         WriteString (value);
264                         WriteEndAttribute ();
265                 }
266
267                 public abstract void WriteBase64 (byte[] buffer, int index, int count);
268
269 #if NET_2_0
270                 public virtual void WriteBinHex (byte [] buffer, int index, int count)
271                 {
272                         StringWriter sw = new StringWriter ();
273                         XmlConvert.WriteBinHex (buffer, index, count, sw);
274                         WriteString (sw.ToString ());
275                 }
276 #else
277                 public abstract void WriteBinHex (byte[] buffer, int index, int count);
278 #endif
279
280                 public abstract void WriteCData (string text);
281
282                 public abstract void WriteCharEntity (char ch);
283
284                 public abstract void WriteChars (char[] buffer, int index, int count);
285
286                 public abstract void WriteComment (string text);
287
288                 public abstract void WriteDocType (string name, string pubid, string sysid, string subset);
289
290                 public void WriteElementString (string localName, string value)
291                 {
292                         WriteStartElement(localName);
293                         WriteString(value);
294                         WriteEndElement();
295                 }
296
297                 public void WriteElementString (string localName, string ns, string value)
298                 {
299                         WriteStartElement(localName, ns);
300                         WriteString(value);
301                         WriteEndElement();
302                 }
303
304 #if NET_2_0
305                 public void WriteElementString (string prefix, string localName, string ns, string value)
306                 {
307                         WriteStartElement(prefix, localName, ns);
308                         WriteString(value);
309                         WriteEndElement();
310                 }
311 #endif
312
313                 public abstract void WriteEndAttribute ();
314
315                 public abstract void WriteEndDocument ();
316
317                 public abstract void WriteEndElement ();
318
319                 public abstract void WriteEntityRef (string name);
320
321                 public abstract void WriteFullEndElement ();
322
323 #if NET_2_0
324                 public virtual void WriteName (string name)
325                 {
326                         WriteNameInternal (name);
327                 }
328
329                 public virtual void WriteNmToken (string name)
330                 {
331                         WriteNmTokenInternal (name);
332                 }
333
334                 public virtual void WriteQualifiedName (string localName, string ns)
335                 {
336                         WriteQualifiedNameInternal (localName, ns);
337                 }
338 #else
339                 public abstract void WriteName (string name);
340
341                 public abstract void WriteNmToken (string name);
342
343                 public abstract void WriteQualifiedName (string localName, string ns);
344 #endif
345
346                 internal void WriteNameInternal (string name)
347                 {
348 #if NET_2_0
349                         switch (Settings.ConformanceLevel) {
350                         case ConformanceLevel.Document:
351                         case ConformanceLevel.Fragment:
352                                 XmlConvert.VerifyName (name);
353                                 break;
354                         }
355 #else
356                         XmlConvert.VerifyName (name);
357 #endif
358                         WriteString (name);
359                 }
360
361                 internal virtual void WriteNmTokenInternal (string name)
362                 {
363 #if NET_2_0
364                         switch (Settings.ConformanceLevel) {
365                         case ConformanceLevel.Document:
366                         case ConformanceLevel.Fragment:
367                                 XmlConvert.VerifyNMTOKEN (name);
368                                 break;
369                         }
370 #else
371                         XmlConvert.VerifyNMTOKEN (name);
372 #endif
373                         WriteString (name);
374                 }
375
376                 internal void WriteQualifiedNameInternal (string localName, string ns)
377                 {
378                         if (localName == null || localName == String.Empty)
379                                 throw new ArgumentException ();
380                         if (ns == null)
381                                 ns = String.Empty;
382
383 #if NET_2_0
384                         switch (Settings.ConformanceLevel) {
385                         case ConformanceLevel.Document:
386                         case ConformanceLevel.Fragment:
387                                 XmlConvert.VerifyNCName (localName);
388                                 break;
389                         }
390 #else
391                         XmlConvert.VerifyNCName (localName);
392 #endif
393
394                         string prefix = ns.Length > 0 ? LookupPrefix (ns) : String.Empty;
395                         if (prefix == null)
396                                 throw new ArgumentException (String.Format ("Namespace '{0}' is not declared.", ns));
397
398                         if (prefix != String.Empty) {
399                                 WriteString (prefix);
400                                 WriteString (":");
401                                 WriteString (localName);
402                         }
403                         else
404                                 WriteString (localName);
405                 }
406
407 #if NET_2_0
408                 [MonoTODO ("defattr handling")]
409                 public virtual void WriteNode (XPathNavigator navigator, bool defattr)
410                 {
411                         if (navigator == null)
412                                 throw new ArgumentNullException ("navigator");
413                         switch (navigator.NodeType) {
414                         case XPathNodeType.Attribute:
415                         case XPathNodeType.Namespace:
416                                 WriteAttributeString (navigator.Prefix, navigator.LocalName, navigator.NamespaceURI, navigator.Value);
417                                 break;
418                         default:
419                                 WriteNode (navigator.ReadSubtree (), defattr);
420                                 break;
421                         }
422                 }
423 #endif
424
425                 public virtual void WriteNode (XmlReader reader, bool defattr)
426                 {
427                         if (reader == null)
428                                 throw new ArgumentException ();
429
430                         if (reader.ReadState == ReadState.Initial) {
431                                 reader.Read ();
432                                 do {
433                                         WriteNode (reader, defattr);
434                                 } while (!reader.EOF);
435                                 return;
436                         }
437
438                         switch (reader.NodeType) {
439                         case XmlNodeType.Element:
440                                 WriteStartElement (reader.Prefix, reader.LocalName, reader.NamespaceURI);
441 #if false
442                                 WriteAttributes (reader, defattr);
443                                 reader.MoveToElement ();
444 #else
445                                 // Well, I found that MS.NET took this way, since
446                                 // there was a error-prone SgmlReader that fails
447                                 // MoveToNextAttribute().
448                                 if (reader.HasAttributes) {
449                                         for (int i = 0; i < reader.AttributeCount; i++) {
450                                                 reader.MoveToAttribute (i);
451                                                 WriteAttribute (reader, defattr);
452                                         }
453                                         reader.MoveToElement ();
454                                 }
455 #endif
456                                 if (reader.IsEmptyElement)
457                                         WriteEndElement ();
458                                 else {
459                                         int depth = reader.Depth;
460                                         reader.Read ();
461                                         if (reader.NodeType != XmlNodeType.EndElement) {
462                                                 do {
463                                                         WriteNode (reader, defattr);
464                                                 } while (depth < reader.Depth);
465                                         }
466                                         WriteFullEndElement ();
467                                 }
468                                 break;
469                         // In case of XmlAttribute, don't proceed reader, and it will never be written.
470                         case XmlNodeType.Attribute:
471                                 return;
472                         case XmlNodeType.Text:
473                                 WriteString (reader.Value);
474                                 break;
475                         case XmlNodeType.CDATA:
476                                 WriteCData (reader.Value);
477                                 break;
478                         case XmlNodeType.EntityReference:
479                                 WriteEntityRef (reader.Name);
480                                 break;
481                         case XmlNodeType.XmlDeclaration:
482                                 // LAMESPEC: It means that XmlWriter implementation _must not_ check
483                                 // whether PI name is "xml" (it is XML error) or not.
484                         case XmlNodeType.ProcessingInstruction:
485                                 WriteProcessingInstruction (reader.Name, reader.Value);
486                                 break;
487                         case XmlNodeType.Comment:
488                                 WriteComment (reader.Value);
489                                 break;
490                         case XmlNodeType.DocumentType:
491                                 WriteDocType (reader.Name,
492                                         reader ["PUBLIC"], reader ["SYSTEM"], reader.Value);
493                                 break;
494                         case XmlNodeType.SignificantWhitespace:
495                                 goto case XmlNodeType.Whitespace;
496                         case XmlNodeType.Whitespace:
497                                 WriteWhitespace (reader.Value);
498                                 break;
499                         case XmlNodeType.EndElement:
500                                 WriteFullEndElement ();
501                                 break;
502                         case XmlNodeType.EndEntity:
503                                 break;
504                         case XmlNodeType.None:
505                                 break;  // Do nothing, nor reporting errors.
506                         default:
507                                 throw new XmlException ("Unexpected node " + reader.Name + " of type " + reader.NodeType);
508                         }
509                         reader.Read ();
510                 }
511
512                 public abstract void WriteProcessingInstruction (string name, string text);
513
514                 public abstract void WriteRaw (string data);
515
516                 public abstract void WriteRaw (char[] buffer, int index, int count);
517
518 #if NET_2_0
519                 public void WriteStartAttribute (string localName)
520                 {
521                         WriteStartAttribute (null, localName, null);
522                 }
523 #endif
524
525                 public void WriteStartAttribute (string localName, string ns)
526                 {
527                         WriteStartAttribute (null, localName, ns);
528                 }
529
530                 public abstract void WriteStartAttribute (string prefix, string localName, string ns);
531
532                 public abstract void WriteStartDocument ();
533
534                 public abstract void WriteStartDocument (bool standalone);
535
536                 public void WriteStartElement (string localName)
537                 {
538                         WriteStartElement (null, localName, null);
539                 }
540
541                 public void WriteStartElement (string localName, string ns)
542                 {
543                         WriteStartElement (null, localName, ns);
544                 }
545
546                 public abstract void WriteStartElement (string prefix, string localName, string ns);
547
548                 public abstract void WriteString (string text);
549
550                 public abstract void WriteSurrogateCharEntity (char lowChar, char highChar);
551
552                 public abstract void WriteWhitespace (string ws);
553
554 #if NET_2_0
555                 [MonoTODO]
556                 public virtual void WriteValue (bool value)
557                 {
558                         WriteString (XQueryConvert.BooleanToString (value));
559                 }
560
561                 [MonoTODO]
562                 public virtual void WriteValue (DateTime value)
563                 {
564                         WriteString (XmlConvert.ToString (value));
565                 }
566
567                 [MonoTODO]
568                 public virtual void WriteValue (decimal value)
569                 {
570                         WriteString (XQueryConvert.DecimalToString (value));
571                 }
572
573                 [MonoTODO]
574                 public virtual void WriteValue (double value)
575                 {
576                         WriteString (XQueryConvert.DoubleToString (value));
577                 }
578
579                 [MonoTODO]
580                 public virtual void WriteValue (int value)
581                 {
582                         WriteString (XQueryConvert.IntToString (value));
583                 }
584
585                 [MonoTODO]
586                 public virtual void WriteValue (long value)
587                 {
588                         WriteString (XQueryConvert.IntegerToString (value));
589                 }
590
591                 [MonoTODO]
592                 public virtual void WriteValue (object value)
593                 {
594                         if (value is string)
595                                 WriteString ((string) value);
596                         else if (value is bool)
597                                 WriteValue ((bool) value);
598                         else if (value is DateTime)
599                                 WriteValue ((DateTime) value);
600                         else if (value is decimal)
601                                 WriteValue ((decimal) value);
602                         else if (value is double)
603                                 WriteValue ((double) value);
604                         else if (value is int)
605                                 WriteValue ((int) value);
606                         else if (value is long)
607                                 WriteValue ((long) value);
608                         else if (value is XmlQualifiedName) {
609                                 XmlQualifiedName qname = (XmlQualifiedName) value;
610                                 WriteQualifiedName (qname.Name, qname.Namespace);
611                         }
612                         else
613                                 throw new NotImplementedException ("Argument value is " + value);
614                 }
615
616                 [MonoTODO]
617                 public virtual void WriteValue (float value)
618                 {
619                         WriteString (XQueryConvert.FloatToString (value));
620                 }
621
622                 [MonoTODO]
623                 public virtual void WriteValue (string value)
624                 {
625                         WriteString (value);
626                 }
627 #endif
628
629                 #endregion
630         }
631 }