2005-01-12 Atsushi Enomoto <atsushi@ximian.com>
[mono.git] / mcs / class / System.XML / System.Xml.Serialization / XmlSerializationWriter.cs
1 //
2 // System.Xml.Serialization.XmlSerializationWriter.cs
3 //
4 // Author:
5 //   Tim Coleman (tim@timcoleman.com)
6 //   Lluis Sanchez Gual (lluis@ximian.com)
7 //
8 // Copyright (C) Tim Coleman, 2002
9 //
10
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 using System;
33 using System.Collections;
34 using System.Globalization;
35 using System.Text;
36 using System.Xml;
37 using System.Xml.Schema;
38 using System.Runtime.Serialization;
39 using System.Reflection;
40
41 namespace System.Xml.Serialization 
42 {
43         public abstract class XmlSerializationWriter 
44 #if NET_2_0
45                 : XmlSerializationGeneratedCode
46 #endif
47         {
48
49                 #region Fields
50
51                 ObjectIDGenerator idGenerator;
52                 int qnameCount;
53                 bool topLevelElement = false;
54
55                 ArrayList namespaces;
56                 XmlWriter writer;
57                 Queue referencedElements;
58                 Hashtable callbacks;
59                 Hashtable serializedObjects;
60                 const string xmlNamespace = "http://www.w3.org/2000/xmlns/";
61                 const string unexpectedTypeError = "The type {0} was not expected. Use the" +
62                         " XmlInclude or SoapInclude attribute to specify types that are not known statically.";
63
64                 #endregion // Fields
65
66                 #region Constructors
67
68                 protected XmlSerializationWriter ()
69                 {
70                         qnameCount = 0;
71                         serializedObjects = new Hashtable ();
72                 }
73                 
74                 internal void Initialize (XmlWriter writer, XmlSerializerNamespaces nss)
75                 {
76                         this.writer = writer;
77                         if (nss != null)
78                         {
79                                 namespaces = new ArrayList ();
80                                 foreach (XmlQualifiedName ns in nss.ToArray())
81                                         if (ns.Name != "" && ns.Namespace != "")
82                                                 namespaces.Add (ns);
83                         }       
84                 }
85
86                 #endregion // Constructors
87
88                 #region Properties
89
90                 protected ArrayList Namespaces {
91                         get { return namespaces; }
92                         set { namespaces = value; }
93                 }
94
95                 protected XmlWriter Writer {
96                         get { return writer; }
97                         set { writer = value; }
98                 }
99
100                 #endregion // Properties
101
102                 #region Methods
103                 
104                 protected void AddWriteCallback (Type type, string typeName, string typeNs, XmlSerializationWriteCallback callback)
105                 {
106                         WriteCallbackInfo info = new WriteCallbackInfo ();
107                         info.Type = type;
108                         info.TypeName = typeName;
109                         info.TypeNs = typeNs;
110                         info.Callback = callback;
111
112                         if (callbacks == null) callbacks = new Hashtable ();
113                         callbacks.Add (type, info);
114                 }
115
116                 protected Exception CreateChoiceIdentifierValueException (string value, string identifier, string name, string ns)
117                 {
118                         string message = string.Format ("Value '{0}' of the choice"
119                                 + " identifier '{1}' does not match element '{2}'"
120                                 + " from namespace '{3}'.", value, identifier,
121                                 name, ns);
122                         return new InvalidOperationException (message);
123                 }
124
125                 protected Exception CreateInvalidChoiceIdentifierValueException (string type, string identifier)
126                 {
127                         string message = string.Format ("Invalid or missing choice"
128                                 + " identifier '{0}' of type '{1}'.", identifier,
129                                 type);
130                         return new InvalidOperationException (message);
131                 }
132
133                 protected Exception CreateMismatchChoiceException (string value, string elementName, string enumValue)
134                 {
135                         string message = String.Format ("Value of {0} mismatches the type of {1}, you need to set it to {2}.", elementName, value, enumValue);
136                         return new InvalidOperationException (message);
137                 }
138
139                 protected Exception CreateUnknownAnyElementException (string name, string ns)
140                 {
141                         string message = String.Format ("The XML element named '{0}' from namespace '{1}' was not expected. The XML element name and namespace must match those provided via XmlAnyElementAttribute(s).", name, ns);
142                         return new InvalidOperationException (message);
143                 }
144
145                 protected Exception CreateUnknownTypeException (object o)
146                 {
147                         return CreateUnknownTypeException (o.GetType ());
148                 }
149
150                 protected Exception CreateUnknownTypeException (Type type)
151                 {
152                         string message = String.Format ("The type {0} may not be used in this context.", type);
153                         return new InvalidOperationException (message);
154                 }
155
156                 protected static byte[] FromByteArrayBase64 (byte[] value)
157                 {
158                         return value;
159                 }
160
161                 protected static string FromByteArrayHex (byte[] value)
162                 {
163                         return XmlCustomFormatter.FromByteArrayHex (value);
164                 }
165
166                 protected static string FromChar (char value)
167                 {
168                         return XmlCustomFormatter.FromChar (value);
169                 }
170
171                 protected static string FromDate (DateTime value)
172                 {
173                         return XmlCustomFormatter.FromDate (value);
174                 }
175
176                 protected static string FromDateTime (DateTime value)
177                 {
178                         return XmlCustomFormatter.FromDateTime (value);
179                 }
180
181                 protected static string FromEnum (long value, string[] values, long[] ids)
182                 {
183                         return XmlCustomFormatter.FromEnum (value, values, ids);
184                 }
185
186                 protected static string FromTime (DateTime value)
187                 {
188                         return XmlCustomFormatter.FromTime (value);
189                 }
190
191                 protected static string FromXmlName (string name)
192                 {
193                         return XmlCustomFormatter.FromXmlName (name);
194                 }
195
196                 protected static string FromXmlNCName (string ncName)
197                 {
198                         return XmlCustomFormatter.FromXmlNCName (ncName);
199                 }
200
201                 protected static string FromXmlNmToken (string nmToken)
202                 {
203                         return XmlCustomFormatter.FromXmlNmToken (nmToken);
204                 }
205
206                 protected static string FromXmlNmTokens (string nmTokens)
207                 {
208                         return XmlCustomFormatter.FromXmlNmTokens (nmTokens);
209                 }
210
211                 protected string FromXmlQualifiedName (XmlQualifiedName xmlQualifiedName)
212                 {
213                         if (xmlQualifiedName == null || xmlQualifiedName == XmlQualifiedName.Empty)
214                                 return null;
215                                 
216                         return GetQualifiedName (xmlQualifiedName.Name, xmlQualifiedName.Namespace);
217                 }
218
219                 private string GetId (object o, bool addToReferencesList)
220                 {
221                         if (idGenerator == null) idGenerator = new ObjectIDGenerator ();
222
223                         bool firstTime;
224                         long lid = idGenerator.GetId (o, out firstTime);
225                         return String.Format (CultureInfo.InvariantCulture, "id{0}", lid);
226                 }
227
228                 
229                 bool AlreadyQueued (object ob)
230                 {
231                         if (idGenerator == null) return false;
232
233                         bool firstTime;
234                         idGenerator.HasId (ob, out firstTime);
235                         return !firstTime;
236                 }
237
238                 private string GetNamespacePrefix (string ns)
239                 {
240                         string prefix = Writer.LookupPrefix (ns);
241                         if (prefix == null) 
242                         {
243                                 prefix = String.Format (CultureInfo.InvariantCulture, "q{0}", ++qnameCount);
244                                 WriteAttribute ("xmlns", prefix, null, ns);
245                         }
246                         return prefix;
247                 }
248
249                 private string GetQualifiedName (string name, string ns)
250                 {
251                         if (ns == String.Empty) return name;
252                         
253                         string prefix = GetNamespacePrefix (ns);
254                         if (prefix == String.Empty)
255                                 return name;
256                         else
257                                 return String.Format ("{0}:{1}", prefix, name);
258                 }
259
260                 protected abstract void InitCallbacks ();
261
262                 protected void TopLevelElement ()
263                 {
264                         topLevelElement = true;
265                 }
266
267                 protected void WriteAttribute (string localName, byte[] value)
268                 {
269                         WriteAttribute (localName, String.Empty, value);
270                 }
271
272                 protected void WriteAttribute (string localName, string value)
273                 {
274                         WriteAttribute (String.Empty, localName, String.Empty, value);
275                 }
276
277                 protected void WriteAttribute (string localName, string ns, byte[] value)
278                 {
279                         if (value == null)
280                                 return;
281
282                         Writer.WriteStartAttribute (localName, ns);
283                         WriteValue (value);
284                         Writer.WriteEndAttribute ();
285                 }
286
287                 protected void WriteAttribute (string localName, string ns, string value)
288                 {
289                         WriteAttribute (null, localName, ns, value);
290                 }
291
292                 protected void WriteAttribute (string prefix, string localName, string ns, string value)
293                 {
294                         if (value == null)
295                                 return;
296
297                         Writer.WriteAttributeString (prefix, localName, ns, value);
298                 }
299
300                 protected void WriteElementEncoded (XmlNode node, string name, string ns, bool isNullable, bool any)
301                 {
302                         if (name != string.Empty)
303                         {
304                                 if (node == null)
305                                 {
306                                         if (isNullable)
307                                                 WriteNullTagEncoded (name, ns);
308                                 }
309                                 else
310                                 {
311                                         Writer.WriteStartElement (name, ns);
312                                         node.WriteTo (Writer);
313                                         Writer.WriteEndElement ();
314                                 }
315                         }
316                         else
317                                 node.WriteTo (Writer);
318                 }
319
320                 protected void WriteElementLiteral (XmlNode node, string name, string ns, bool isNullable, bool any)
321                 {
322                         if (name != string.Empty)
323                         {
324                                 if (node == null)
325                                 {
326                                         if (isNullable)
327                                                 WriteNullTagLiteral (name, ns);
328                                 }
329                                 else
330                                 {
331                                         Writer.WriteStartElement (name, ns);
332                                         node.WriteTo (Writer);
333                                         Writer.WriteEndElement ();
334                                 }
335                         }
336                         else
337                                 node.WriteTo (Writer);
338                 }
339
340                 protected void WriteElementQualifiedName (string localName, XmlQualifiedName value)
341                 {
342                         WriteElementQualifiedName (localName, String.Empty, value, null);
343                 }
344
345                 protected void WriteElementQualifiedName (string localName, string ns, XmlQualifiedName value)
346                 {
347                         WriteElementQualifiedName (localName, ns, value, null);
348                 }
349
350                 protected void WriteElementQualifiedName (string localName, XmlQualifiedName value, XmlQualifiedName xsiType)
351                 {
352                         WriteElementQualifiedName (localName, String.Empty, value, xsiType);
353                 }
354
355                 protected void WriteElementQualifiedName (string localName, string ns, XmlQualifiedName value, XmlQualifiedName xsiType)
356                 {
357                         localName = XmlCustomFormatter.FromXmlNCName (localName);
358                         WriteStartElement (localName, ns);
359                         if (xsiType != null) WriteXsiType (xsiType.Name, xsiType.Namespace);
360                         Writer.WriteString (FromXmlQualifiedName (value));
361                         WriteEndElement ();
362                 }
363
364                 protected void WriteElementString (string localName, string value)
365                 {
366                         WriteElementString (localName, String.Empty, value, null);
367                 }
368
369                 protected void WriteElementString (string localName, string ns, string value)
370                 {
371                         WriteElementString (localName, ns, value, null);
372                 }
373
374                 protected void WriteElementString (string localName, string value, XmlQualifiedName xsiType)
375                 {
376                         WriteElementString (localName, String.Empty, value, xsiType);
377                 }
378
379                 protected void WriteElementString (string localName, string ns, string value, XmlQualifiedName xsiType)
380                 {
381                         if (value == null) return;
382
383                         if (xsiType != null) {
384                                 localName = XmlCustomFormatter.FromXmlNCName (localName);
385                                 WriteStartElement (localName, ns);
386                                 WriteXsiType (xsiType.Name, xsiType.Namespace);
387                                 Writer.WriteString (value);
388                                 WriteEndElement ();
389                         } 
390                         else
391                                 Writer.WriteElementString (localName, ns, value);
392                 }
393
394                 protected void WriteElementStringRaw (string localName, byte[] value)
395                 {
396                         WriteElementStringRaw (localName, String.Empty, value, null);
397                 }
398
399                 protected void WriteElementStringRaw (string localName, string value)
400                 {
401                         WriteElementStringRaw (localName, String.Empty, value, null);
402                 }
403
404                 protected void WriteElementStringRaw (string localName, byte[] value, XmlQualifiedName xsiType)
405                 {
406                         WriteElementStringRaw (localName, String.Empty, value, xsiType);
407                 }
408
409                 protected void WriteElementStringRaw (string localName, string ns, byte[] value)
410                 {
411                         WriteElementStringRaw (localName, ns, value, null);
412                 }
413
414                 protected void WriteElementStringRaw (string localName, string ns, string value)
415                 {
416                         WriteElementStringRaw (localName, ns, value, null);
417                 }
418
419                 protected void WriteElementStringRaw (string localName, string value, XmlQualifiedName xsiType)
420                 {
421                         WriteElementStringRaw (localName, String.Empty, value, null);
422                 }
423
424                 protected void WriteElementStringRaw (string localName, string ns, byte[] value, XmlQualifiedName xsiType)
425                 {
426                         if (value == null)
427                                 return;
428
429                         WriteStartElement (localName, ns);
430
431                         if (xsiType != null)
432                                 WriteXsiType (xsiType.Name, xsiType.Namespace);
433
434                         if (value.Length > 0) 
435                                 Writer.WriteBase64(value,0,value.Length);
436                         WriteEndElement ();
437                 }
438
439                 protected void WriteElementStringRaw (string localName, string ns, string value, XmlQualifiedName xsiType)
440                 {
441                         localName = XmlCustomFormatter.FromXmlNCName (localName);
442                         WriteStartElement (localName, ns);
443
444                         if (xsiType != null)
445                                 WriteXsiType (xsiType.Name, xsiType.Namespace);
446
447                         Writer.WriteRaw (value);
448                         WriteEndElement ();
449                 }
450
451                 protected void WriteEmptyTag (string name)
452                 {
453                         WriteEmptyTag (name, String.Empty);
454                 }
455
456                 protected void WriteEmptyTag (string name, string ns)
457                 {
458                         name = XmlCustomFormatter.FromXmlName (name);
459                         WriteStartElement (name, ns);
460                         WriteEndElement ();
461                 }
462
463                 protected void WriteEndElement ()
464                 {
465                         WriteEndElement (null);
466                 }
467
468                 protected void WriteEndElement (object o)
469                 {
470                         if (o != null)
471                                 serializedObjects.Remove (o);
472                                 
473                         Writer.WriteEndElement ();
474                 }
475
476                 protected void WriteId (object o)
477                 {
478                         WriteAttribute ("id", GetId (o, true));
479                 }
480
481                 protected void WriteNamespaceDeclarations (XmlSerializerNamespaces ns)
482                 {
483                         if (ns == null)
484                                 return;
485
486                         ICollection namespaces = ns.Namespaces.Values;
487                         foreach (XmlQualifiedName qn in namespaces) {
488                                 if (qn.Namespace != String.Empty && Writer.LookupPrefix (qn.Namespace) != qn.Name)
489                                         WriteAttribute ("xmlns", qn.Name, xmlNamespace, qn.Namespace);
490                         }
491                 }
492
493                 protected void WriteNullableQualifiedNameEncoded (string name, string ns, XmlQualifiedName value, XmlQualifiedName xsiType)
494                 {
495                         if (value != null)
496                                 WriteElementQualifiedName (name, ns, value, xsiType);
497                         else
498                                 WriteNullTagEncoded (name, ns);
499                 }
500
501                 protected void WriteNullableQualifiedNameLiteral (string name, string ns, XmlQualifiedName value)
502                 {
503                         if (value != null)
504                                 WriteElementQualifiedName (name, ns, value);
505                         else
506                                 WriteNullTagLiteral (name, ns);
507                 }
508
509                 protected void WriteNullableStringEncoded (string name, string ns, string value, XmlQualifiedName xsiType)
510                 {
511                         if (value != null)
512                                 WriteElementString (name, ns, value, xsiType);
513                         else
514                                 WriteNullTagEncoded (name, ns);
515                 }
516
517                 protected void WriteNullableStringEncodedRaw (string name, string ns, byte[] value, XmlQualifiedName xsiType)
518                 {
519                         if (value == null)
520                                 WriteNullTagEncoded (name, ns);
521                         else
522                                 WriteElementStringRaw (name, ns, value, xsiType);
523                 }
524
525                 protected void WriteNullableStringEncodedRaw (string name, string ns, string value, XmlQualifiedName xsiType)
526                 {
527                         if (value == null)
528                                 WriteNullTagEncoded (name, ns);
529                         else
530                                 WriteElementStringRaw (name, ns, value, xsiType);
531                 }
532
533                 protected void WriteNullableStringLiteral (string name, string ns, string value)
534                 {
535                         if (value != null)
536                                 WriteElementString (name, ns, value, null);
537                         else
538                                 WriteNullTagLiteral (name, ns);
539                 }
540
541                 protected void WriteNullableStringLiteralRaw (string name, string ns, byte[] value)
542                 {
543                         if (value == null)
544                                 WriteNullTagLiteral (name, ns);
545                         else
546                                 WriteElementStringRaw (name, ns, value);
547                 }
548
549                 protected void WriteNullableStringLiteralRaw (string name, string ns, string value)
550                 {
551                         if (value == null)
552                                 WriteNullTagLiteral (name, ns);
553                         else
554                                 WriteElementStringRaw (name, ns, value);
555                 }
556
557                 protected void WriteNullTagEncoded (string name)
558                 {
559                         WriteNullTagEncoded (name, String.Empty);
560                 }
561
562                 protected void WriteNullTagEncoded (string name, string ns)
563                 {
564                         Writer.WriteStartElement (name, ns);
565 #if NET_1_1
566                         Writer.WriteAttributeString ("nil", XmlSchema.InstanceNamespace, "true");
567 #else
568                         Writer.WriteAttributeString ("null", XmlSchema.InstanceNamespace, "1");
569 #endif
570                         Writer.WriteEndElement ();
571                 }
572
573                 protected void WriteNullTagLiteral (string name)
574                 {
575                         WriteNullTagLiteral (name, String.Empty);
576                 }
577
578                 protected void WriteNullTagLiteral (string name, string ns)
579                 {
580                         WriteStartElement (name, ns);
581                         Writer.WriteAttributeString ("nil", XmlSchema.InstanceNamespace, "true");
582                         WriteEndElement ();
583                 }
584
585                 protected void WritePotentiallyReferencingElement (string n, string ns, object o)
586                 {
587                         WritePotentiallyReferencingElement (n, ns, o, null, false, false);
588                 }
589
590                 protected void WritePotentiallyReferencingElement (string n, string ns, object o, Type ambientType)
591                 {
592                         WritePotentiallyReferencingElement (n, ns, o, ambientType, false, false);
593                 }
594
595                 protected void WritePotentiallyReferencingElement (string n, string ns, object o, Type ambientType, bool suppressReference)
596                 {
597                         WritePotentiallyReferencingElement (n, ns, o, ambientType, suppressReference, false);
598                 }
599
600                 protected void WritePotentiallyReferencingElement (string n, string ns, object o, Type ambientType, bool suppressReference, bool isNullable)
601                 {
602                         if (o == null) 
603                         {
604                                 if (isNullable) WriteNullTagEncoded (n, ns);
605                                 return;
606                         }
607
608                         WriteStartElement (n, ns, true);
609
610                         CheckReferenceQueue ();
611
612                         if (callbacks.ContainsKey (o.GetType ()))
613                         {
614                                 WriteCallbackInfo info = (WriteCallbackInfo) callbacks[o.GetType()];
615                                 if (o.GetType ().IsEnum) {
616                                         info.Callback (o);
617                                 }
618                                 else if (suppressReference) {
619                                         Writer.WriteAttributeString ("id", GetId (o, false));
620                                         if (ambientType != o.GetType ()) WriteXsiType(info.TypeName, info.TypeNs);
621                                         info.Callback (o);
622                                 }
623                                 else {
624                                         if (!AlreadyQueued (o)) referencedElements.Enqueue (o);
625                                         Writer.WriteAttributeString ("href", "#" + GetId (o, true));
626                                 }
627                         }
628                         else
629                         {
630                                 // Must be a primitive type
631                                 TypeData td = TypeTranslator.GetTypeData (o.GetType ());
632                                 if (td.SchemaType != SchemaTypes.Primitive)
633                                         throw new InvalidOperationException ("Invalid type: " + o.GetType().FullName);
634                                 WriteXsiType(td.XmlType, XmlSchema.Namespace);
635                                 Writer.WriteString (XmlCustomFormatter.ToXmlString (td, o));
636                         }
637
638                         WriteEndElement ();
639                 }
640
641                 protected void WriteReferencedElements ()
642                 {
643                         if (referencedElements == null) return;
644                         if (callbacks == null) return;
645
646                         while (referencedElements.Count > 0)
647                         {
648                                 object o = referencedElements.Dequeue ();
649                                 TypeData td = TypeTranslator.GetTypeData (o.GetType ());
650                                 WriteCallbackInfo info = (WriteCallbackInfo) callbacks[o.GetType()];
651                                 WriteStartElement (info.TypeName, info.TypeNs, true);
652                                 Writer.WriteAttributeString ("id", GetId (o, false));
653
654                                 if (td.SchemaType != SchemaTypes.Array) // Array use its own "arrayType" attribute
655                                         WriteXsiType(info.TypeName, info.TypeNs);
656
657                                 info.Callback (o);
658                                 WriteEndElement ();
659                         }
660                 }
661
662                 protected void WriteReferencingElement (string n, string ns, object o)
663                 {
664                         WriteReferencingElement (n, ns, o, false);
665                 }
666
667                 protected void WriteReferencingElement (string n, string ns, object o, bool isNullable)
668                 {
669                         if (o == null) 
670                         {
671                                 if (isNullable) WriteNullTagEncoded (n, ns);
672                                 return;
673                         }
674                         else
675                         {
676                                 CheckReferenceQueue ();
677                                 if (!AlreadyQueued (o)) referencedElements.Enqueue (o);
678
679                                 Writer.WriteStartElement (n, ns);
680                                 Writer.WriteAttributeString ("href", "#" + GetId (o, true));
681                                 Writer.WriteEndElement ();
682                         }
683                 }
684
685                 void CheckReferenceQueue ()
686                 {
687                         if (referencedElements == null)  
688                         {
689                                 referencedElements = new Queue ();
690                                 InitCallbacks ();
691                         }
692                 }
693
694                 [MonoTODO]
695                 protected void WriteRpcResult (string name, string ns)
696                 {
697                         throw new NotImplementedException ();
698                 }
699
700                 protected void WriteSerializable (IXmlSerializable serializable, string name, string ns, bool isNullable)
701                 {
702                         if (serializable == null)
703                         {
704                                 if (isNullable) WriteNullTagLiteral (name, ns);
705                                 return;
706                         }
707                         else
708                         {
709                                 Writer.WriteStartElement (name, ns);
710                                 serializable.WriteXml (Writer);
711                                 Writer.WriteEndElement ();
712                         }
713                 }
714
715                 protected void WriteStartDocument ()
716                 {
717                         if (Writer.WriteState == WriteState.Start)
718                                 Writer.WriteStartDocument ();
719                 }
720
721                 protected void WriteStartElement (string name)
722                 {
723                         WriteStartElement (name, String.Empty, null, false);
724                 }
725
726                 protected void WriteStartElement (string name, string ns)
727                 {
728                         WriteStartElement (name, ns, null, false);
729                 }
730
731                 protected void WriteStartElement (string name, string ns, bool writePrefixed)
732                 {
733                         WriteStartElement (name, ns, null, writePrefixed);
734                 }
735
736                 protected void WriteStartElement (string name, string ns, object o)
737                 {
738                         WriteStartElement (name, ns, o, false);
739                 }
740
741                 protected void WriteStartElement (string name, string ns, object o, bool writePrefixed)
742                 {
743                         if (o != null)
744                         {
745                                 if (serializedObjects.Contains (o))
746                                         throw new InvalidOperationException ("A cirtular reference was detected while serializing an object of type " + o.GetType().Name);
747                                 else
748                                         serializedObjects [o] = o;
749                         }
750                         
751                         string prefix = null;
752                         
753                         if (topLevelElement && ns != null && ns.Length != 0)
754                         {
755                                 foreach (XmlQualifiedName qn in namespaces)
756                                         if (qn.Namespace == ns) {
757                                                 prefix = qn.Name;
758                                                 writePrefixed = true;
759                                                 break;
760                                         }
761                         }
762
763                         if (writePrefixed && ns != string.Empty)
764                         {
765                                 name = XmlCustomFormatter.FromXmlName (name);
766                                 
767                                 if (prefix == null)
768                                         prefix = Writer.LookupPrefix (ns);
769                                 if (prefix == null || prefix.Length == 0)
770                                         prefix = "q" + (++qnameCount);
771                                 Writer.WriteStartElement (prefix, name, ns);
772                         } else
773                                 Writer.WriteStartElement (name, ns);
774
775                         if (topLevelElement) 
776                         {
777                                 if (namespaces != null) {
778                                         foreach (XmlQualifiedName qn in namespaces)
779                                         {
780                                                 string currentPrefix = Writer.LookupPrefix (qn.Namespace);
781                                                 if (currentPrefix != null && currentPrefix.Length != 0) continue;
782                                                 
783                                                 WriteAttribute ("xmlns",qn.Name,xmlNamespace,qn.Namespace);
784                                         }
785                                 }
786                                 topLevelElement = false;
787                         }
788                 }
789
790                 protected void WriteTypedPrimitive (string name, string ns, object o, bool xsiType)
791                 {
792                         string value;
793                         TypeData td = TypeTranslator.GetTypeData (o.GetType ());
794
795                         name = XmlCustomFormatter.FromXmlName (name);
796                         Writer.WriteStartElement (name, ns);
797
798                         if (o is XmlQualifiedName)
799                                 value = FromXmlQualifiedName ((XmlQualifiedName) o);
800                         else
801                                 value = XmlCustomFormatter.ToXmlString (td, o);
802
803                         if (xsiType)
804                         {
805                                 if (td.SchemaType != SchemaTypes.Primitive)
806                                         throw new InvalidOperationException (string.Format (unexpectedTypeError, o.GetType().FullName));
807                                 WriteXsiType (td.XmlType, XmlSchema.Namespace);
808                         }
809
810                         WriteValue (value);
811                         Writer.WriteEndElement ();
812                 }
813
814                 protected void WriteValue (byte[] value)
815                 {
816                         Writer.WriteBase64 (value, 0, value.Length);
817                 }
818
819                 protected void WriteValue (string value)
820                 {
821                         if (value != null)
822                                 Writer.WriteString (value);
823                 }
824
825                 protected void WriteXmlAttribute (XmlNode node)
826                 {
827                         WriteXmlAttribute (node, null);
828                 }
829
830                 protected void WriteXmlAttribute (XmlNode node, object container)
831                 {
832                         XmlAttribute attr = node as XmlAttribute;
833                         if (attr == null)
834                                 throw new InvalidOperationException ("The node must be either type XmlAttribute or a derived type.");
835                         
836                         if (attr.NamespaceURI == XmlSerializer.WsdlNamespace)
837                         {
838                                 // The wsdl arrayType attribute needs special handling
839                                 if (attr.LocalName == "arrayType") {
840                                         string ns, type, dimensions;
841                                         TypeTranslator.ParseArrayType (attr.Value, out type, out ns, out dimensions);
842                                         string value = GetQualifiedName (type + dimensions, ns);
843                                         WriteAttribute (attr.Prefix, attr.LocalName, attr.NamespaceURI, value);
844                                         return;
845                                 }
846                         }
847                         
848                         WriteAttribute (attr.Prefix, attr.LocalName, attr.NamespaceURI, attr.Value);
849                 }
850
851                 protected void WriteXsiType (string name, string ns)
852                 {
853                         if (ns != null && ns != string.Empty)
854                                 WriteAttribute ("type", XmlSchema.InstanceNamespace, GetQualifiedName (name, ns));
855                         else
856                                 WriteAttribute ("type", XmlSchema.InstanceNamespace, name);
857                 }
858                 
859 #if NET_2_0
860
861                 [MonoTODO]
862                 protected Exception CreateInvalidAnyTypeException (object o)
863                 {
864                         throw new NotImplementedException ();
865                 }
866                 
867                 [MonoTODO]
868                 protected Exception CreateInvalidAnyTypeException (Type t)
869                 {
870                         throw new NotImplementedException ();
871                 }
872
873                 [MonoTODO]
874                 protected Exception CreateInvalidEnumValueException (object value, string typeName)
875                 {
876                         throw new NotImplementedException ();
877                 }
878
879                 [MonoTODO]
880                 protected static string FromEnum (long value, string[] values, long[] ids, string typeName)
881                 {
882                         throw new NotImplementedException ();
883                 }
884
885                 [MonoTODO]
886                 protected string FromXmlQualifiedName (XmlQualifiedName xmlQualifiedName, bool ignoreEmpty)
887                 {
888                         throw new NotImplementedException ();
889                 }
890                 
891                 [MonoTODO]
892                 protected static Assembly ResolveDynamicAssembly (string assemblyFullName)
893                 {
894                         throw new NotImplementedException ();
895                 }
896                 
897                 [MonoTODO]
898                 protected void WriteSerializable (IXmlSerializable serializable, string name, string ns, bool isNullable, bool any)
899                 {
900                         throw new NotImplementedException ();
901                 }
902                 
903                 [MonoTODO]
904                 protected bool EscapeName
905                 {
906                         get { throw new NotImplementedException(); }
907                         set { throw new NotImplementedException(); }
908                 }
909 #endif
910                 
911                 #endregion
912
913                 class WriteCallbackInfo
914                 {
915                         public Type Type;
916                         public string TypeName;
917                         public string TypeNs;
918                         public XmlSerializationWriteCallback Callback;
919                 }
920         }
921 }