2 // System.Xml.XmlWriter
5 // Kral Ferch <kral_ferch@hotmail.com>
6 // Atsushi Enomoto <ginga@kit.hi-ho.ne.jp>
9 // (C) 2002-2003 Atsushi Enomoto
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:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
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.
37 using System.Xml.XPath;
43 public abstract class XmlWriter : IDisposable
45 public abstract class XmlWriter
49 XmlWriterSettings settings;
54 protected XmlWriter () { }
61 public virtual XmlWriterSettings Settings {
64 settings = new XmlWriterSettings ();
70 public abstract WriteState WriteState { get; }
74 public virtual string XmlLang {
78 public virtual XmlSpace XmlSpace {
79 get { return XmlSpace.None; }
82 public abstract string XmlLang { get; }
84 public abstract XmlSpace XmlSpace { get; }
91 public abstract void Close ();
94 public static XmlWriter Create (Stream stream)
96 return Create (stream, null);
99 public static XmlWriter Create (string file)
101 return Create (file, null);
104 public static XmlWriter Create (TextWriter writer)
106 return Create (writer, null);
109 public static XmlWriter Create (XmlWriter writer)
111 return Create (writer, null);
114 public static XmlWriter Create (StringBuilder builder)
116 return Create (builder, null);
119 public static XmlWriter Create (Stream stream, XmlWriterSettings settings)
121 Encoding enc = settings != null ? settings.Encoding : Encoding.UTF8;
122 return Create (new StreamWriter (stream, enc), settings);
125 public static XmlWriter Create (string file, XmlWriterSettings settings)
127 Encoding enc = settings != null ? settings.Encoding : Encoding.UTF8;
128 return Create (new StreamWriter (file, false, enc), settings);
131 public static XmlWriter Create (StringBuilder builder, XmlWriterSettings settings)
133 return Create (new StringWriter (builder), settings);
136 public static XmlWriter Create (TextWriter writer, XmlWriterSettings settings)
138 return CreateTextWriter (writer, settings);
141 public static XmlWriter Create (XmlWriter writer, XmlWriterSettings settings)
143 if (settings == null)
144 settings = new XmlWriterSettings ();
145 writer.settings = settings;
149 private static XmlWriter CreateTextWriter (TextWriter writer, XmlWriterSettings settings)
151 if (settings == null)
152 settings = new XmlWriterSettings ();
153 XmlTextWriter xtw = new XmlTextWriter (writer, settings);
154 return Create (xtw, settings);
157 protected virtual void Dispose (bool disposing)
162 void IDisposable.Dispose ()
168 public abstract void Flush ();
170 public abstract string LookupPrefix (string ns);
172 private void WriteAttribute (XmlReader reader, bool defattr)
174 if (!defattr && reader.IsDefault)
177 WriteStartAttribute (reader.Prefix, reader.LocalName, reader.NamespaceURI);
178 while (reader.ReadAttributeValue ()) {
179 switch (reader.NodeType) {
180 case XmlNodeType.Text:
181 WriteString (reader.Value);
183 case XmlNodeType.EntityReference:
184 WriteEntityRef (reader.Name);
188 WriteEndAttribute ();
191 public virtual void WriteAttributes (XmlReader reader, bool defattr)
194 throw new ArgumentException("null XmlReader specified.", "reader");
196 switch (reader.NodeType) {
197 case XmlNodeType.XmlDeclaration:
198 WriteAttributeString ("version", reader ["version"]);
199 if (reader ["encoding"] != null)
200 WriteAttributeString ("encoding", reader ["encoding"]);
201 if (reader ["standalone"] != null)
202 WriteAttributeString ("standalone", reader ["standalone"]);
204 case XmlNodeType.Element:
205 if (reader.MoveToFirstAttribute ())
206 goto case XmlNodeType.Attribute;
208 case XmlNodeType.Attribute:
210 WriteAttribute (reader, defattr);
211 } while (reader.MoveToNextAttribute ());
212 reader.MoveToElement ();
215 throw new XmlException("NodeType is not one of Element, Attribute, nor XmlDeclaration.");
219 public void WriteAttributeString (string localName, string value)
221 WriteAttributeString ("", localName, null, value);
224 public void WriteAttributeString (string localName, string ns, string value)
226 WriteAttributeString ("", localName, ns, value);
229 public void WriteAttributeString (string prefix, string localName, string ns, string value)
231 // In MS.NET (1.0), this check is done *here*, not at WriteStartAttribute.
232 // (XmlTextWriter.WriteStartAttribute("xmlns", "anyname", null) throws an exception.
234 WriteStartAttribute (prefix, localName, ns);
235 if (value != null && value.Length > 0)
237 WriteEndAttribute ();
240 public abstract void WriteBase64 (byte[] buffer, int index, int count);
243 public virtual void WriteBinHex (byte [] buffer, int index, int count)
245 StringWriter sw = new StringWriter ();
246 XmlConvert.WriteBinHex (buffer, index, count, sw);
247 WriteString (sw.ToString ());
250 public abstract void WriteBinHex (byte[] buffer, int index, int count);
253 public abstract void WriteCData (string text);
255 public abstract void WriteCharEntity (char ch);
257 public abstract void WriteChars (char[] buffer, int index, int count);
259 public abstract void WriteComment (string text);
261 public abstract void WriteDocType (string name, string pubid, string sysid, string subset);
263 public void WriteElementString (string localName, string value)
265 WriteStartElement(localName);
266 if (value != null && value.Length > 0)
271 public void WriteElementString (string localName, string ns, string value)
273 WriteStartElement(localName, ns);
274 if (value != null && value.Length > 0)
280 public void WriteElementString (string prefix, string localName, string ns, string value)
282 WriteStartElement(prefix, localName, ns);
283 if (value != null && value.Length > 0)
289 public abstract void WriteEndAttribute ();
291 public abstract void WriteEndDocument ();
293 public abstract void WriteEndElement ();
295 public abstract void WriteEntityRef (string name);
297 public abstract void WriteFullEndElement ();
300 public virtual void WriteName (string name)
302 WriteNameInternal (name);
305 public virtual void WriteNmToken (string name)
307 WriteNmTokenInternal (name);
310 public virtual void WriteQualifiedName (string localName, string ns)
312 WriteQualifiedNameInternal (localName, ns);
315 public abstract void WriteName (string name);
317 public abstract void WriteNmToken (string name);
319 public abstract void WriteQualifiedName (string localName, string ns);
322 internal void WriteNameInternal (string name)
325 switch (Settings.ConformanceLevel) {
326 case ConformanceLevel.Document:
327 case ConformanceLevel.Fragment:
328 XmlConvert.VerifyName (name);
332 XmlConvert.VerifyName (name);
337 internal virtual void WriteNmTokenInternal (string name)
341 switch (Settings.ConformanceLevel) {
342 case ConformanceLevel.Document:
343 case ConformanceLevel.Fragment:
344 valid = XmlChar.IsNmToken (name);
348 valid = XmlChar.IsNmToken (name);
351 throw new ArgumentException ("Argument name is not a valid NMTOKEN.");
355 internal void WriteQualifiedNameInternal (string localName, string ns)
357 if (localName == null || localName == String.Empty)
358 throw new ArgumentException ();
363 switch (Settings.ConformanceLevel) {
364 case ConformanceLevel.Document:
365 case ConformanceLevel.Fragment:
366 XmlConvert.VerifyNCName (localName);
370 XmlConvert.VerifyNCName (localName);
373 string prefix = ns.Length > 0 ? LookupPrefix (ns) : String.Empty;
375 throw new ArgumentException (String.Format ("Namespace '{0}' is not declared.", ns));
377 if (prefix != String.Empty) {
378 WriteString (prefix);
380 WriteString (localName);
383 WriteString (localName);
387 [MonoTODO] // FIXME: test defattr handling
388 public virtual void WriteNode (XPathNavigator navigator, bool defattr)
390 if (navigator == null)
391 throw new ArgumentNullException ("navigator");
392 switch (navigator.NodeType) {
393 case XPathNodeType.Attribute:
394 case XPathNodeType.Namespace:
395 if (defattr || navigator.SchemaInfo == null ||
396 !navigator.SchemaInfo.IsDefault)
397 WriteAttributeString (navigator.Prefix,
399 navigator.NamespaceURI,
402 case XPathNodeType.Text:
403 WriteString (navigator.Value);
405 case XPathNodeType.SignificantWhitespace:
406 WriteWhitespace (navigator.Value);
408 case XPathNodeType.Whitespace:
409 WriteWhitespace (navigator.Value);
411 case XPathNodeType.Comment:
412 WriteComment (navigator.Value);
414 case XPathNodeType.ProcessingInstruction:
415 WriteProcessingInstruction (navigator.Name, navigator.Value);
417 case XPathNodeType.Root:
418 if (navigator.MoveToFirstChild ()) {
420 WriteNode (navigator, defattr);
421 } while (navigator.MoveToNext ());
422 navigator.MoveToParent ();
425 case XPathNodeType.Element:
426 WriteStartElement (navigator.Prefix, navigator.LocalName, navigator.NamespaceURI);
427 if (navigator.MoveToFirstNamespace (XPathNamespaceScope.Local)) {
429 WriteNode (navigator, defattr);
430 } while (navigator.MoveToNextNamespace (XPathNamespaceScope.Local));
431 navigator.MoveToParent ();
433 if (navigator.MoveToFirstAttribute ()) {
435 WriteNode (navigator, defattr);
436 } while (navigator.MoveToNextAttribute ());
437 navigator.MoveToParent ();
439 if (navigator.MoveToFirstChild ()) {
441 WriteNode (navigator, defattr);
442 } while (navigator.MoveToNext ());
443 navigator.MoveToParent ();
445 if (navigator.IsEmptyElement)
448 WriteFullEndElement ();
451 throw new NotSupportedException ();
456 public virtual void WriteNode (XmlReader reader, bool defattr)
459 throw new ArgumentException ();
461 if (reader.ReadState == ReadState.Initial) {
464 WriteNode (reader, defattr);
465 } while (!reader.EOF);
469 switch (reader.NodeType) {
470 case XmlNodeType.Element:
471 WriteStartElement (reader.Prefix, reader.LocalName, reader.NamespaceURI);
473 WriteAttributes (reader, defattr);
474 reader.MoveToElement ();
476 // Well, I found that MS.NET took this way, since
477 // there was a error-prone SgmlReader that fails
478 // MoveToNextAttribute().
479 if (reader.HasAttributes) {
480 for (int i = 0; i < reader.AttributeCount; i++) {
481 reader.MoveToAttribute (i);
482 WriteAttribute (reader, defattr);
484 reader.MoveToElement ();
487 if (reader.IsEmptyElement)
490 int depth = reader.Depth;
492 if (reader.NodeType != XmlNodeType.EndElement) {
494 WriteNode (reader, defattr);
495 } while (depth < reader.Depth);
497 WriteFullEndElement ();
500 // In case of XmlAttribute, don't proceed reader, and it will never be written.
501 case XmlNodeType.Attribute:
503 case XmlNodeType.Text:
504 WriteString (reader.Value);
506 case XmlNodeType.CDATA:
507 WriteCData (reader.Value);
509 case XmlNodeType.EntityReference:
510 WriteEntityRef (reader.Name);
512 case XmlNodeType.XmlDeclaration:
513 // LAMESPEC: It means that XmlWriter implementation _must not_ check
514 // whether PI name is "xml" (it is XML error) or not.
515 case XmlNodeType.ProcessingInstruction:
516 WriteProcessingInstruction (reader.Name, reader.Value);
518 case XmlNodeType.Comment:
519 WriteComment (reader.Value);
521 case XmlNodeType.DocumentType:
522 WriteDocType (reader.Name,
523 reader ["PUBLIC"], reader ["SYSTEM"], reader.Value);
525 case XmlNodeType.SignificantWhitespace:
526 goto case XmlNodeType.Whitespace;
527 case XmlNodeType.Whitespace:
528 WriteWhitespace (reader.Value);
530 case XmlNodeType.EndElement:
531 WriteFullEndElement ();
533 case XmlNodeType.EndEntity:
535 case XmlNodeType.None:
536 break; // Do nothing, nor reporting errors.
538 throw new XmlException ("Unexpected node " + reader.Name + " of type " + reader.NodeType);
543 public abstract void WriteProcessingInstruction (string name, string text);
545 public abstract void WriteRaw (string data);
547 public abstract void WriteRaw (char[] buffer, int index, int count);
550 public void WriteStartAttribute (string localName)
552 WriteStartAttribute (null, localName, null);
556 public void WriteStartAttribute (string localName, string ns)
558 WriteStartAttribute (null, localName, ns);
561 public abstract void WriteStartAttribute (string prefix, string localName, string ns);
563 public abstract void WriteStartDocument ();
565 public abstract void WriteStartDocument (bool standalone);
567 public void WriteStartElement (string localName)
569 WriteStartElement (null, localName, null);
572 public void WriteStartElement (string localName, string ns)
574 WriteStartElement (null, localName, ns);
577 public abstract void WriteStartElement (string prefix, string localName, string ns);
579 public abstract void WriteString (string text);
581 public abstract void WriteSurrogateCharEntity (char lowChar, char highChar);
583 public abstract void WriteWhitespace (string ws);
587 public virtual void WriteValue (bool value)
589 WriteString (XQueryConvert.BooleanToString (value));
593 public virtual void WriteValue (DateTime value)
595 WriteString (XmlConvert.ToString (value));
599 public virtual void WriteValue (decimal value)
601 WriteString (XQueryConvert.DecimalToString (value));
605 public virtual void WriteValue (double value)
607 WriteString (XQueryConvert.DoubleToString (value));
611 public virtual void WriteValue (int value)
613 WriteString (XQueryConvert.IntToString (value));
617 public virtual void WriteValue (long value)
619 WriteString (XQueryConvert.IntegerToString (value));
623 public virtual void WriteValue (object value)
626 WriteString ((string) value);
627 else if (value is bool)
628 WriteValue ((bool) value);
629 else if (value is DateTime)
630 WriteValue ((DateTime) value);
631 else if (value is decimal)
632 WriteValue ((decimal) value);
633 else if (value is double)
634 WriteValue ((double) value);
635 else if (value is int)
636 WriteValue ((int) value);
637 else if (value is long)
638 WriteValue ((long) value);
639 else if (value is XmlQualifiedName) {
640 XmlQualifiedName qname = (XmlQualifiedName) value;
641 WriteQualifiedName (qname.Name, qname.Namespace);
644 throw new NotImplementedException ("Argument value is " + value);
648 public virtual void WriteValue (float value)
650 WriteString (XQueryConvert.FloatToString (value));
654 public virtual void WriteValue (string value)