New test.
[mono.git] / mcs / class / System.Data / System.Data / XmlSchemaDataImporter.cs
1 //
2 // XmlSchemaDataImporter.cs
3 //
4 // Author:
5 //      Atsushi Enomoto <atsushi@ximian.com>
6 //
7 // (C)2004 Novell Inc.
8 //
9 //
10 // ***** The design note became somewhat obsolete. Should be rewritten. *****
11 //
12 // * Design Notes
13 //
14 // ** Abstract
15 //
16 //      This class is used to import an XML Schema into a DataSet schema.
17 //
18 //      Only XmlReader is acceptable as the input to the class.
19 //      This class is not expected to read XML Schema multi time.
20 //
21 // ** Targetable Schema Components
22 //
23 //      Only global global elements that hold complex type are converted 
24 //      into a table. 
25 //      <del>
26 //      The components of the type of the element are subsequently converted
27 //      into a table, BUT there is an exception. As for "DataSet elements",
28 //      the type is just ignored (see "DataSet Element definition" below).
29 //      </del><ins>
30 //      The components of the type of the element are subsequently converted
31 //      into a table. As for "DataSet elements", its complex type is also 
32 //      handled.
33 //      </ins>
34 //
35 //      Unused complex types are never be converted.
36 //
37 //      Global simple types and global attributes are never converted.
38 //      They cannot be a table.
39 //      Local complex types are also converted into a table.
40 //
41 //      Local elements are converted into either a table or a column in
42 //      the "context DataTable". Simple-typed element is not always converted
43 //      into a DataColumn; if maxOccurs > 1, it will be converted as a table.
44 //
45 // ** Name Convention
46 //
47 //      Ignore this section. Microsoft.NET was buggy enough to confuse
48 //      against these name conflicts.
49 //
50 //      Since local complex types are anonymous, we have to name for each
51 //      component. Thus, and since complex types and elements can have the 
52 //      same name each other, we have to manage a table for mappings from 
53 //      a name to a component. The names must be also used in DataRelation
54 //      definitions correctly.
55 //
56 // ** DataSet element definition
57 //
58 //      "DataSet element" is 1) such element that has an attribute 
59 //      msdata:IsDataSet (where prefix "msdata" is bound to 
60 //      urn:schemas-microsoft-com:xml-msdata), or 2) the only one
61 //      element definition in the schema.
62 //
63 //      There is another complicated rule. 1) If there is only one element EL 
64 //      in the schema, and 2) if the type of EL is complex named CT, and 3)
65 //      the content of the CT is a group base, and 4) the group base contains 
66 //      an element EL2, and finally 5) if EL2 is complex, THEN the element is
67 //      the DataSet element.
68 //
69 //      Only the first global element that matches the condition above is
70 //      regarded as DataSet element (by necessary design or just a bug?) 
71 //      instead of handling as an error.
72 //
73 //      All global elements are considered as an alternative in the dataset
74 //      element.
75 //
76 //      For local elements, msdata:IsDataSet are just ignored.
77 //
78 // ** Importing Complex Types as Columns
79 //
80 //      When an xs:element is going to be mapped, its complex type (remember
81 //      that only complex-typed elements are targettable) are expanded to
82 //      DataColumn.
83 //
84 //      DataColumn has a property MappingType that shows whether this column
85 //       came from attribute or element.
86 //
87 //      [Question: How about MappingType.Simple? How is it used?]
88 //
89 //      Additionally, for particle elements, it might also create another
90 //      DataTable (but for the particle elements in context DataTable, it
91 //      will create an index to the new table).
92 //
93 //      For group base particles (XmlSchemaGroupBase; sequence, choice, all)
94 //      each component in those groups are mapped to a column. Even if you
95 //      import "choice" or "all" components, DataSet.WriteXmlSchema() will
96 //      output them just as a "sequence".
97 //
98 //      Columns cannot be added directly to current context DataTable; they
99 //      need to be added after processing all the columns, because they may
100 //      have msdata:Ordinal attribute that specifies the order of the columns
101 //      in the DataTable.
102 //
103 //      "Nested elements" are not allowed. (Clarification required?)
104 //
105 // ** Identity Constraints and DataRelations
106 //
107 // *** DataRelations from element identity constraints
108 //
109 //      Only constraints on "DataSet element" is considered. All other
110 //      constraint definitions are ignored. Note that it is DataSet that has
111 //      the property Relations (of type DataRelationCollection).
112 //
113 //      xs:key and xs:unique are handled as the same (then both will be
114 //      serialized as xs:unique).
115 //
116 //      The XPath expressions in the constraints are strictly limited; they
117 //      are expected to be expandable enough to be mappable for each
118 //
119 //              * selector to "any_valid_XPath/is/OK/blah" 
120 //                where "blah" is one of the DataTable name. It looks that
121 //                only the last QName section is significant and any heading
122 //                XPath step is OK (even if the mapped node does not exist).
123 //              * field to QName that is mapped to DataColumn in the DataTable
124 //                (even ./QName is not allowed)
125 //
126 // *** DataRelations from annotations
127 //
128 //      See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/_mapping_relationship_specified_for_nested_elements.asp and http://msdn.microsoft.com/library/en-us/cpguide/html/_specifying_relationship_between_elements_with_no_nesting.asp
129 //
130 // ** Informative References
131 //
132 // Generating DataSet Relational Structure from XML Schema (XSD)
133 // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/_generating_dataset_relational_structure_from_xsd.asp
134 //
135
136 //
137 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
138 //
139 // Permission is hereby granted, free of charge, to any person obtaining
140 // a copy of this software and associated documentation files (the
141 // "Software"), to deal in the Software without restriction, including
142 // without limitation the rights to use, copy, modify, merge, publish,
143 // distribute, sublicense, and/or sell copies of the Software, and to
144 // permit persons to whom the Software is furnished to do so, subject to
145 // the following conditions:
146 // 
147 // The above copyright notice and this permission notice shall be
148 // included in all copies or substantial portions of the Software.
149 // 
150 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
151 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
152 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
153 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
154 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
155 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
156 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
157 //
158
159 using System;
160 using System.Collections;
161 using System.Data;
162 using System.Globalization;
163 using System.Xml;
164 using System.Xml.Schema;
165
166
167 namespace System.Data
168 {
169         internal class TableStructureCollection : CollectionBase
170         {
171                 public void Add (TableStructure table)
172                 {
173                         List.Add (table);
174                 }
175
176                 public TableStructure this [int i] {
177                         get { return List [i] as TableStructure; }
178                 }
179
180                 public TableStructure this [string name] {
181                         get {
182                                 foreach (TableStructure ts in List)
183                                         if (ts.Table.TableName == name)
184                                                 return ts;
185                                 return null;
186                         }
187                 }
188         }
189
190         internal class RelationStructureCollection : CollectionBase
191         {
192                 public void Add (RelationStructure rel)
193                 {
194                         List.Add (rel);
195                 }
196
197                 public RelationStructure this [int i] {
198                         get { return List [i] as RelationStructure; }
199                 }
200
201                 public RelationStructure this [string parent, string child] {
202                         get {
203                                 foreach (RelationStructure rel in List)
204                                         if (rel.ParentTableName == parent && rel.ChildTableName == child)
205                                                 return rel;
206                                 return null;
207                         }
208                 }
209         }
210
211         internal class TableStructure
212         {
213                 public TableStructure (DataTable table)
214                 {
215                         this.Table = table;
216                 }
217
218                 // The columns and orders which will be added to the context
219                 // table (See design notes; Because of the ordinal problem)
220                 public DataTable Table;
221                 public Hashtable OrdinalColumns = new Hashtable ();
222                 public ArrayList NonOrdinalColumns = new ArrayList ();
223                 public DataColumn PrimaryKey;
224
225                 public bool ContainsColumn (string name)
226                 {
227                         foreach (DataColumn col in NonOrdinalColumns)
228                                 if (col.ColumnName == name)
229                                         return true;
230                         foreach (DataColumn col in OrdinalColumns.Keys)
231                                 if (col.ColumnName == name)
232                                         return true;
233                         return false;
234                 }
235         }
236
237         internal class RelationStructure
238         {
239                 public string ExplicitName;
240                 public string ParentTableName;
241                 public string ChildTableName;
242                 public string ParentColumnName;
243                 public string ChildColumnName;
244                 public bool IsNested;
245                 public bool CreateConstraint;
246         }
247
248         internal class ConstraintStructure
249         {
250                 public readonly string TableName;
251                 public readonly string [] Columns;
252                 public readonly bool [] IsAttribute;
253                 public readonly string ConstraintName;
254                 public readonly bool IsPrimaryKey;
255                 public readonly string ReferName;
256                 public readonly bool IsNested;
257                 public readonly bool IsConstraintOnly;
258
259                 public ConstraintStructure (string tname, string [] cols, bool [] isAttr, string cname, bool isPK, string refName, bool isNested, bool isConstraintOnly)
260                 {
261                         TableName = tname;
262                         Columns = cols;
263                         IsAttribute = isAttr;
264                         ConstraintName = XmlHelper.Decode (cname);
265                         IsPrimaryKey = isPK;
266                         ReferName = refName;
267                         IsNested = isNested;
268                         IsConstraintOnly = isConstraintOnly;
269                 }
270         }
271
272         internal class XmlSchemaDataImporter
273         {
274                 static readonly XmlSchemaDatatype schemaIntegerType;
275                 static readonly XmlSchemaDatatype schemaDecimalType;
276                 static readonly XmlSchemaComplexType schemaAnyType;
277
278                 static XmlSchemaDataImporter ()
279                 {
280                         XmlSchema s = new XmlSchema ();
281                         XmlSchemaAttribute a = new XmlSchemaAttribute ();
282                         a.Name = "foo";
283                         a.SchemaTypeName = new XmlQualifiedName ("integer", XmlSchema.Namespace);
284                         s.Items.Add (a);
285                         XmlSchemaAttribute b = new XmlSchemaAttribute ();
286                         b.Name = "bar";
287                         b.SchemaTypeName = new XmlQualifiedName ("decimal", XmlSchema.Namespace);
288                         s.Items.Add (b);
289                         XmlSchemaElement e = new XmlSchemaElement ();
290                         e.Name = "bar";
291                         s.Items.Add (e);
292                         s.Compile (null);
293                         schemaIntegerType = a.AttributeType as XmlSchemaDatatype;
294                         schemaDecimalType = b.AttributeType as XmlSchemaDatatype;
295                         schemaAnyType = e.ElementType as XmlSchemaComplexType;
296                 }
297
298                 #region Fields
299
300                 DataSet dataset;
301                 XmlSchema schema;
302
303                 ArrayList relations = new ArrayList ();
304                 Hashtable reservedConstraints = new Hashtable ();
305
306                 // such element that has an attribute msdata:IsDataSet="true"
307                 XmlSchemaElement datasetElement;
308
309                 // choice alternatives in the "dataset element"
310                 ArrayList topLevelElements = new ArrayList ();
311
312                 // import target elements
313                 ArrayList targetElements = new ArrayList ();
314
315                 TableStructure currentTable;
316
317                 #endregion
318
319                 // .ctor()
320
321                 public XmlSchemaDataImporter (DataSet dataset, XmlReader reader)
322                 {
323                         this.dataset = dataset;
324                         dataset.DataSetName = "NewDataSet"; // Initialize always
325                         schema = XmlSchema.Read (reader, null);
326                         if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "schema" && reader.NamespaceURI == XmlSchema.Namespace)
327                                 reader.ReadEndElement ();
328                         schema.Compile (null);
329                 }
330
331                 // methods
332
333                 public void Process ()
334                 {
335                         if (schema.Id != null)
336                                 dataset.DataSetName = schema.Id; // default. Overridable by "DataSet element"
337                         dataset.Namespace = schema.TargetNamespace;
338
339                         // Find dataset element
340                         foreach (XmlSchemaObject obj in schema.Items) {
341                                 XmlSchemaElement el = obj as XmlSchemaElement;
342                                 if (el != null) {
343                                         if (datasetElement == null &&
344                                                 IsDataSetElement (el))
345                                                 datasetElement = el;
346                                         if (el.ElementType is XmlSchemaComplexType &&
347 el.ElementType != schemaAnyType)
348                                                 targetElements.Add (obj);
349                                 }
350                         }
351
352                         // make reservation of identity constraints
353                         if (datasetElement != null) {
354                                 // keys/uniques.
355                                 foreach (XmlSchemaObject obj in datasetElement.Constraints)
356                                         if (! (obj is XmlSchemaKeyref))
357                                                 ReserveSelfIdentity ((XmlSchemaIdentityConstraint) obj);
358                                 // keyrefs.
359                                 foreach (XmlSchemaObject obj in datasetElement.Constraints)
360                                         if (obj is XmlSchemaKeyref)
361                                                 ReserveRelationIdentity (datasetElement, (XmlSchemaKeyref) obj);
362                         }
363
364                         foreach (XmlSchemaObject obj in schema.Items) {
365                                 if (obj is XmlSchemaElement) {
366                                         XmlSchemaElement el = obj as XmlSchemaElement;
367                                         if (el.ElementType is XmlSchemaComplexType &&
368 el.ElementType != schemaAnyType)
369                                                 targetElements.Add (obj);
370                                 }
371                         }
372
373                         // This collection will grow up while processing elements.
374                         int globalElementCount = targetElements.Count;
375
376                         for (int i = 0; i < globalElementCount; i++)
377                                 ProcessGlobalElement ((XmlSchemaElement) targetElements [i]);
378
379                         // Rest are local elements.
380                         for (int i = globalElementCount; i < targetElements.Count; i++)
381                                 ProcessDataTableElement ((XmlSchemaElement) targetElements [i]);
382
383                         // Handle relation definitions written as xs:annotation.
384                         // See detail: http://msdn.microsoft.com/library/shared/happyUrl/fnf_msdn.asp?Redirect=%22http://msdn.microsoft.com/404/default.asp%22
385                         foreach (XmlSchemaObject obj in schema.Items)
386                                 if (obj is XmlSchemaAnnotation)
387                                         HandleAnnotations ((XmlSchemaAnnotation) obj, false);
388
389                         if (datasetElement != null) {
390                                 // Handle constraints in the DataSet element. First keys.
391                                 foreach (XmlSchemaObject obj in datasetElement.Constraints)
392                                         if (! (obj is XmlSchemaKeyref))
393                                                 ProcessSelfIdentity (reservedConstraints [obj] as ConstraintStructure);
394                                 // Then keyrefs.
395                                 foreach (XmlSchemaObject obj in datasetElement.Constraints)
396                                         if (obj is XmlSchemaKeyref)
397                                                 ProcessRelationIdentity (datasetElement, reservedConstraints [obj] as ConstraintStructure);
398                         }
399
400                         foreach (RelationStructure rs in this.relations)
401                                 dataset.Relations.Add (GenerateRelationship (rs));
402                 }
403
404                 private bool IsDataSetElement (XmlSchemaElement el)
405                 {
406                         if (el.UnhandledAttributes != null) {
407                                 foreach (XmlAttribute attr in el.UnhandledAttributes) {
408                                         if (attr.LocalName == "IsDataSet" &&
409                                                 attr.NamespaceURI == XmlConstants.MsdataNamespace) {
410                                                 switch (attr.Value) {
411                                                 case "true": // case sensitive
412                                                         return true;
413                                                 case "false":
414                                                         break;
415                                                 default:
416                                                         throw new DataException (String.Format ("Value {0} is invalid for attribute 'IsDataSet'.", attr.Value));
417                                                 }
418                                         }
419                                 }
420                         }
421
422                         if (schema.Elements.Count != 1)
423                                 return false;
424                         if (!(el.SchemaType is XmlSchemaComplexType))
425                                 return false;
426                         XmlSchemaComplexType ct = (XmlSchemaComplexType) el.SchemaType;
427                         if (ct.AttributeUses.Count > 0)
428                                 return false;
429                         XmlSchemaGroupBase gb = ct.ContentTypeParticle as XmlSchemaGroupBase;
430                         if (gb == null || gb.Items.Count == 0)
431                                 return false;
432                         foreach (XmlSchemaParticle p in gb.Items) {
433                                 if (ContainsColumn (p))
434                                         return false;
435                         }
436                         return true;
437                 }
438
439                 private bool ContainsColumn (XmlSchemaParticle p)
440                 {
441                         XmlSchemaElement el = p as XmlSchemaElement;
442                         if (el != null) {
443                                 XmlSchemaComplexType ct = el.ElementType as XmlSchemaComplexType;
444                                 if (ct == null || ct == schemaAnyType)
445                                         return true; // column element
446                                 if (ct.AttributeUses.Count > 0)
447                                         return false; // table element
448                                 if (ct.ContentType == XmlSchemaContentType.TextOnly)
449                                         return true; // column element
450                                 else
451                                         return false; // table element
452                         }
453                         XmlSchemaGroupBase gb = p as XmlSchemaGroupBase;
454                         for (int i = 0; i < gb.Items.Count; i++) {
455                                 if (ContainsColumn ((XmlSchemaParticle) gb.Items [i]))
456                                         return true;
457                         }
458                         return false;
459                 }
460
461                 private void ProcessGlobalElement (XmlSchemaElement el)
462                 {
463                         // If it is already registered (by resolving reference
464                         // in previously-imported elements), just ignore.
465                         if (dataset.Tables.Contains (el.QualifiedName.Name))
466                                 return;
467
468                         // If type is not complex, just skip this element
469                         if (! (el.ElementType is XmlSchemaComplexType && el.ElementType != schemaAnyType))
470                                 return;
471
472                         if (IsDataSetElement (el)) {
473                                 ProcessDataSetElement (el);
474                                 return;
475                         }
476
477                         // Register as a top-level element
478                         topLevelElements.Add (el);
479                         // Create DataTable for this element
480                         ProcessDataTableElement (el);
481                 }
482
483                 private void ProcessDataSetElement (XmlSchemaElement el)
484                 {
485                         dataset.DataSetName = el.Name;
486                         this.datasetElement = el;
487
488                         // Search for msdata:Locale attribute
489                         if (el.UnhandledAttributes != null) {
490                                 foreach (XmlAttribute attr in el.UnhandledAttributes) {
491                                         if (attr.LocalName == "Locale" &&
492                                                 attr.NamespaceURI == XmlConstants.MsdataNamespace) {
493                                                 CultureInfo ci = new CultureInfo (attr.Value);
494                                                 dataset.Locale = ci;
495                                         }
496                                 }
497                         }
498
499                         // Process content type particle (and create DataTable)
500                         XmlSchemaComplexType ct = el.ElementType as XmlSchemaComplexType;
501                         XmlSchemaParticle p = ct != null ? ct.ContentTypeParticle : null;
502                         if (p != null)
503                                 HandleDataSetContentTypeParticle (p);
504                 }
505
506                 private void HandleDataSetContentTypeParticle (XmlSchemaParticle p)
507                 {
508                         XmlSchemaElement el = p as XmlSchemaElement;
509                         if (el != null) {
510                                 if (el.ElementType is XmlSchemaComplexType && el.RefName != el.QualifiedName)
511                                         ProcessDataTableElement (el);
512                         }
513                         else if (p is XmlSchemaGroupBase) {
514                                 foreach (XmlSchemaParticle pc in ((XmlSchemaGroupBase) p).Items)
515                                         HandleDataSetContentTypeParticle (pc);
516                         }
517                 }
518
519                 private void ProcessDataTableElement (XmlSchemaElement el)
520                 {
521                         string tableName = XmlHelper.Decode (el.QualifiedName.Name);
522                         // If it is already registered, just ignore.
523                         if (dataset.Tables.Contains (tableName))
524                                 return;
525
526                         DataTable table = new DataTable (tableName);
527                         table.Namespace = el.QualifiedName.Namespace;
528                         currentTable = new TableStructure (table);
529
530                         dataset.Tables.Add (table);
531
532                         // Find Locale
533                         if (el.UnhandledAttributes != null) {
534                                 foreach (XmlAttribute attr in el.UnhandledAttributes) {
535                                         if (attr.LocalName == "Locale" &&
536                                                 attr.NamespaceURI == XmlConstants.MsdataNamespace)
537                                                 table.Locale = new CultureInfo (attr.Value);
538                                 }
539                         }
540
541                         // Handle complex type (NOTE: It is (or should be)
542                         // impossible the type is other than complex type).
543                         XmlSchemaComplexType ct = (XmlSchemaComplexType) el.ElementType;
544
545                         // Handle attributes
546                         foreach (DictionaryEntry de in ct.AttributeUses)
547                                 ImportColumnAttribute ((XmlSchemaAttribute) de.Value);
548
549                         // Handle content type particle
550                         if (ct.ContentTypeParticle is XmlSchemaElement)
551                                 ImportColumnElement (el, (XmlSchemaElement) ct.ContentTypeParticle);
552                         else if (ct.ContentTypeParticle is XmlSchemaGroupBase)
553                                 ImportColumnGroupBase (el, (XmlSchemaGroupBase) ct.ContentTypeParticle);
554                         // else if null then do nothing.
555
556                         // Handle simple content
557                         switch (ct.ContentType) {
558                         case XmlSchemaContentType.TextOnly:
559 //                      case XmlSchemaContentType.Mixed:
560                                 // LAMESPEC: When reading from XML Schema, it maps to "_text", while on the data inference, it is mapped to "_Text" (case ignorant).
561                                 string simpleName = el.QualifiedName.Name + "_text";
562                                 DataColumn simple = new DataColumn (simpleName);
563                                 simple.Namespace = el.QualifiedName.Namespace;
564                                 simple.AllowDBNull = (el.MinOccurs == 0);
565                                 simple.ColumnMapping = MappingType.SimpleContent;
566                                 simple.DataType = ConvertDatatype (ct.Datatype);
567                                 currentTable.NonOrdinalColumns.Add (simple);
568                                 break;
569                         }
570
571                         // add columns to the table in specified order 
572                         // (by msdata:Ordinal attributes)
573                         SortedList sd = new SortedList ();
574                         foreach (DictionaryEntry de in currentTable.OrdinalColumns)
575                                 sd.Add (de.Value, de.Key);
576                         foreach (DictionaryEntry de in sd)
577                                 table.Columns.Add ((DataColumn) de.Value);
578                         foreach (DataColumn dc in currentTable.NonOrdinalColumns)
579                                 table.Columns.Add (dc);
580                 }
581
582                 private DataRelation GenerateRelationship (RelationStructure rs)
583                 {
584                         DataTable ptab = dataset.Tables [rs.ParentTableName];
585                         DataTable ctab = dataset.Tables [rs.ChildTableName];
586
587                         DataRelation rel ;
588                         string name = rs.ExplicitName != null ? rs.ExplicitName : XmlHelper.Decode (ptab.TableName) + '_' + XmlHelper.Decode (ctab.TableName);
589
590                         // Annotation Relations belonging to a DataSet can contain multiple colnames
591                         // in parentkey and childkey.
592                         if (datasetElement != null) {
593                                 String[] pcolnames = rs.ParentColumnName.Split (null);
594                                 String[] ccolnames = rs.ChildColumnName.Split (null);
595
596                                 DataColumn[] pcol = new DataColumn [pcolnames.Length];
597                                 for (int i=0; i<pcol.Length; ++i)
598                                         pcol [i] = ptab.Columns [XmlHelper.Decode (pcolnames [i])];
599
600                                 DataColumn[] ccol = new DataColumn [ccolnames.Length];
601                                 for (int i=0; i < ccol.Length; ++i) {
602                                         ccol [i] = ctab.Columns [XmlHelper.Decode (ccolnames [i])];
603                                         if (ccol [i] == null)
604                                                 ccol [i] = CreateChildColumn (pcol [i], ctab);
605                                 }
606                                 rel = new DataRelation (name, pcol, ccol, rs.CreateConstraint);
607                         } else {
608                                 DataColumn pcol = ptab.Columns [XmlHelper.Decode (rs.ParentColumnName)];
609                                 DataColumn ccol = ctab.Columns [XmlHelper.Decode (rs.ChildColumnName)];
610                                 if (ccol == null) 
611                                         ccol = CreateChildColumn (pcol, ctab);
612                                 rel = new DataRelation (name, pcol, ccol, rs.CreateConstraint);
613                         }
614                         rel.Nested = rs.IsNested;
615                         if (rs.CreateConstraint)
616                                 rel.ParentTable.PrimaryKey = rel.ParentColumns;
617                         return rel;
618                 }
619
620                 private DataColumn CreateChildColumn (DataColumn parentColumn, DataTable childTable)
621                 {
622                         DataColumn col = childTable.Columns.Add (parentColumn.ColumnName, 
623                                                                 parentColumn.DataType);
624                         col.Namespace = String.Empty;
625                         col.ColumnMapping = MappingType.Hidden;
626                         return col;
627                 }
628
629                 private void ImportColumnGroupBase (XmlSchemaElement parent, XmlSchemaGroupBase gb)
630                 {
631                         foreach (XmlSchemaParticle p in gb.Items) {
632                                 XmlSchemaElement el = p as XmlSchemaElement;
633                                 if (el != null)
634                                         ImportColumnElement (parent, el);
635                                 else if (p is XmlSchemaGroupBase)
636                                         ImportColumnGroupBase (parent, (XmlSchemaGroupBase) p);
637                                 // otherwise p is xs:any
638                         }
639                 }
640
641                 private XmlSchemaDatatype GetSchemaPrimitiveType (object type)
642                 {
643                         if (type is XmlSchemaComplexType)
644                                 return null; // It came here, so that maybe it is xs:anyType
645                         XmlSchemaDatatype dt = type as XmlSchemaDatatype;
646                         if (dt == null && type != null)
647                                 dt = ((XmlSchemaSimpleType) type).Datatype;
648                         return dt;
649                 }
650
651                 // Note that this column might be Hidden
652                 private void ImportColumnAttribute (XmlSchemaAttribute attr)
653                 {
654                         DataColumn col = new DataColumn ();
655                         col.ColumnName = attr.QualifiedName.Name;
656                         col.Namespace = attr.QualifiedName.Namespace;
657                         XmlSchemaDatatype dt = GetSchemaPrimitiveType (attr.AttributeType);
658                         // This complicated check comes from the fact that
659                         // MS.NET fails to map System.Object to anyType (that
660                         // will cause ReadTypedObject() fail on XmlValidatingReader).
661                         // ONLY In DataSet context, we set System.String for
662                         // simple ur-type.
663                         col.DataType = ConvertDatatype (dt);
664                         if (col.DataType == typeof (object))
665                                 col.DataType = typeof (string);
666                         // When attribute use="prohibited", then it is regarded as 
667                         // Hidden column.
668                         if (attr.Use == XmlSchemaUse.Prohibited)
669                                 col.ColumnMapping = MappingType.Hidden;
670                         else {
671                                 col.ColumnMapping = MappingType.Attribute;
672                                 col.DefaultValue = GetAttributeDefaultValue (attr);
673                         }
674                         if (attr.Use == XmlSchemaUse.Required)
675                                 col.AllowDBNull = false;
676
677                         FillFacet (col, attr.AttributeType as XmlSchemaSimpleType);
678
679                         // Call this method after filling the name
680                         ImportColumnMetaInfo (attr, attr.QualifiedName, col);
681                         AddColumn (col);
682                 }
683
684                 private void ImportColumnElement (XmlSchemaElement parent, XmlSchemaElement el)
685                 {
686                         // FIXME: element nest check
687
688                         DataColumn col = new DataColumn ();
689                         col.DefaultValue = GetElementDefaultValue (el);
690                         col.AllowDBNull = (el.MinOccurs == 0);
691
692                         if (el.ElementType is XmlSchemaComplexType && el.ElementType != schemaAnyType)
693                                 FillDataColumnComplexElement (parent, el, col);
694                         else if (el.MaxOccurs != 1)
695                                 FillDataColumnRepeatedSimpleElement (parent, el, col);
696                         else
697                                 FillDataColumnSimpleElement (el, col);
698                 }
699
700                 // common process for element and attribute
701                 private void ImportColumnMetaInfo (XmlSchemaAnnotated obj, XmlQualifiedName name, DataColumn col)
702                 {
703                         int ordinal = -1;
704                         if (obj.UnhandledAttributes != null) {
705                                 foreach (XmlAttribute attr in obj.UnhandledAttributes) {
706                                         if (attr.NamespaceURI != XmlConstants.MsdataNamespace)
707                                                 continue;
708                                         switch (attr.LocalName) {
709                                         case XmlConstants.Caption:
710                                                 col.Caption = attr.Value;
711                                                 break;
712                                         case XmlConstants.DataType:
713                                                 col.DataType = Type.GetType (attr.Value);
714                                                 break;
715                                         case XmlConstants.AutoIncrement:
716                                                 col.AutoIncrement = bool.Parse (attr.Value);
717                                                 break;
718                                         case XmlConstants.AutoIncrementSeed:
719                                                 col.AutoIncrementSeed = int.Parse (attr.Value);
720                                                 break;
721                                         case XmlConstants.AutoIncrementStep:
722                                                 col.AutoIncrementStep = int.Parse (attr.Value);
723                                                 break;
724                                         case XmlConstants.ReadOnly:
725                                                 col.ReadOnly = XmlConvert.ToBoolean (attr.Value);
726                                                 break;
727                                         case XmlConstants.Ordinal:
728                                                 ordinal = int.Parse (attr.Value);
729                                                 break;
730                                         }
731                                 }
732                         }
733                 }
734
735                 private void FillDataColumnComplexElement (XmlSchemaElement parent, XmlSchemaElement el, DataColumn col)
736                 {
737                         if (targetElements.Contains (el))
738                                 return; // do nothing
739
740                         string elName = XmlHelper.Decode (el.QualifiedName.Name);
741                         if (elName == dataset.DataSetName)
742                                 // Well, why it is ArgumentException :-?
743                                 throw new ArgumentException ("Nested element must not have the same name as DataSet's name.");
744
745                         if (el.Annotation != null)
746                                 HandleAnnotations (el.Annotation, true);
747                         // If xsd:keyref xsd:key for this table exists, then don't add
748                         // relation here manually.
749                         else if (!DataSetDefinesKey (elName)) {
750                                 AddParentKeyColumn (parent, el, col);
751
752                                 RelationStructure rel = new RelationStructure ();
753                                 rel.ParentTableName = XmlHelper.Decode (parent.QualifiedName.Name);
754                                 rel.ChildTableName = elName;
755                                 rel.ParentColumnName = col.ColumnName;
756                                 rel.ChildColumnName = col.ColumnName;
757                                 rel.CreateConstraint = true;
758                                 rel.IsNested = true;
759                                 relations.Add (rel);
760                         }
761
762                         // If the element is not referenced one, the element will be handled later.
763                         if (el.RefName == XmlQualifiedName.Empty)
764                                 targetElements.Add (el);
765
766                 }
767
768                 private bool DataSetDefinesKey (string name)
769                 {
770                         foreach (ConstraintStructure c in reservedConstraints.Values)
771                                 if (c.TableName == name && (c.IsPrimaryKey || c.IsNested))
772                                         return true;
773                         return false;
774                 }
775
776                 private void AddParentKeyColumn (XmlSchemaElement parent, XmlSchemaElement el, DataColumn col)
777                 {
778                         if (currentTable.PrimaryKey != null)
779                                 return;
780
781                         // check name identity
782                         string name = XmlHelper.Decode (parent.QualifiedName.Name) + "_Id";
783                         int count = 0;
784                         while (currentTable.ContainsColumn (name))
785                                 name = String.Format ("{0}_{1}", name, count++);
786                         // check existing primary key
787                         if (currentTable.Table.PrimaryKey.Length > 0)
788                                 throw new DataException (String.Format ("There is already primary key columns in the table \"{0}\".", currentTable.Table.TableName));
789
790                         col.ColumnName = name;
791                         col.ColumnMapping = MappingType.Hidden;
792                         col.Namespace = parent.QualifiedName.Namespace;
793                         col.DataType = typeof (int);
794                         col.AutoIncrement = true;
795                         col.AllowDBNull = false;
796
797                         ImportColumnMetaInfo (el, el.QualifiedName, col);
798                         AddColumn (col);
799                         currentTable.PrimaryKey = col;
800                 }
801
802                 private void FillDataColumnRepeatedSimpleElement (XmlSchemaElement parent, XmlSchemaElement el, DataColumn col)
803                 {
804                         if (targetElements.Contains (el))
805                                 return; // do nothing
806
807                         AddParentKeyColumn (parent, el, col);
808                         DataColumn pkey = currentTable.PrimaryKey;
809
810                         string elName = XmlHelper.Decode (el.QualifiedName.Name);
811                         string parentName = XmlHelper.Decode (parent.QualifiedName.Name);
812
813                         DataTable dt = new DataTable ();
814                         dt.TableName = elName;
815                         dt.Namespace = el.QualifiedName.Namespace;
816                         // reference key column to parent
817                         DataColumn cc = new DataColumn ();
818                         cc.ColumnName = parentName + "_Id";
819                         cc.Namespace = parent.QualifiedName.Namespace;
820                         cc.ColumnMapping = MappingType.Hidden;
821                         cc.DataType = typeof (int);
822
823                         // repeatable content simple element
824                         DataColumn cc2 = new DataColumn ();
825                         cc2.ColumnName = elName + "_Column";
826                         cc2.Namespace = el.QualifiedName.Namespace;
827                         cc2.ColumnMapping = MappingType.SimpleContent;
828                         cc2.AllowDBNull = false;
829                         cc2.DataType = ConvertDatatype (GetSchemaPrimitiveType (el.ElementType));
830
831                         dt.Columns.Add (cc2);
832                         dt.Columns.Add (cc);
833                         dataset.Tables.Add (dt);
834
835                         RelationStructure rel = new RelationStructure ();
836                         rel.ParentTableName = parentName;
837                         rel.ChildTableName = dt.TableName;
838                         rel.ParentColumnName = pkey.ColumnName;
839                         rel.ChildColumnName = cc.ColumnName;
840                         rel.IsNested = true;
841                         rel.CreateConstraint = true;
842                         relations.Add (rel);
843                 }
844
845                 private void FillDataColumnSimpleElement (XmlSchemaElement el, DataColumn col)
846                 {
847                         col.ColumnName = XmlHelper.Decode (el.QualifiedName.Name);
848                         col.Namespace = el.QualifiedName.Namespace;
849                         col.ColumnMapping = MappingType.Element;
850                         col.DataType = ConvertDatatype (GetSchemaPrimitiveType (el.ElementType));
851                         FillFacet (col, el.ElementType as XmlSchemaSimpleType);
852
853                         ImportColumnMetaInfo (el, el.QualifiedName, col);
854
855                         AddColumn (col);
856                 }
857
858                 private void AddColumn (DataColumn col)
859                 {
860                         if (col.Ordinal < 0)
861                                 currentTable.NonOrdinalColumns.Add (col);
862                         else
863                                 currentTable.OrdinalColumns.Add (col, col.Ordinal);
864                 }
865
866                 private void FillFacet (DataColumn col, XmlSchemaSimpleType st)
867                 {
868                         if (st == null || st.Content == null)
869                                 return;
870
871                         // Handle restriction facets
872
873                         XmlSchemaSimpleTypeRestriction restriction = st == null ? null : st.Content as XmlSchemaSimpleTypeRestriction;
874                         if (restriction == null)
875                                 throw new DataException ("DataSet does not suport 'list' nor 'union' simple type.");
876
877                         foreach (XmlSchemaFacet f in restriction.Facets) {
878                                 if (f is XmlSchemaMaxLengthFacet)
879                                         // There is no reason why MaxLength is limited to int, except for the fact that DataColumn.MaxLength property is int.
880                                         col.MaxLength = int.Parse (f.Value);
881                         }
882                 }
883
884                 private Type ConvertDatatype (XmlSchemaDatatype dt)
885                 {
886                         if (dt == null)
887                                 return typeof (string);
888                         else if (dt.ValueType == typeof (decimal)) {
889                                 // LAMESPEC: MSDN documentation says it is based 
890                                 // on ValueType. However, in the System.Xml.Schema
891                                 // context, xs:integer is mapped to Decimal, while
892                                 // in DataSet context it is mapped to Int64.
893                                 if (dt == schemaDecimalType)
894                                         return typeof (decimal);
895                                 else if (dt == schemaIntegerType)
896                                         return typeof (long);
897                                 else
898                                         return typeof (ulong);
899                         }
900                         else
901                                 return dt.ValueType;
902                 }
903
904                 // This method cuts out the local name of the last step from XPath.
905                 // It is nothing more than hack. However, MS looks to do similar.
906                 private string GetSelectorTarget (string xpath)
907                 {
908                         string tableName = xpath;
909                         int index = tableName.LastIndexOf ('/');
910                         // '>' is enough. If XPath [0] = '/', it is invalid. 
911                         // Selector can specify only element axes.
912                         if (index > 0)
913                                 tableName = tableName.Substring (index + 1);
914
915                         // Round QName to NSName
916                         index = tableName.LastIndexOf (':');
917                         if (index > 0)
918                                 tableName = tableName.Substring (index + 1);
919
920                         return XmlHelper.Decode (tableName);
921                 }
922
923                 private void ReserveSelfIdentity (XmlSchemaIdentityConstraint ic)
924                 {
925                         string tableName = GetSelectorTarget (ic.Selector.XPath);
926
927                         string [] cols = new string [ic.Fields.Count];
928                         bool [] isAttrSpec = new bool [cols.Length];
929
930                         int i = 0;
931                         foreach (XmlSchemaXPath Field in ic.Fields) {
932                                 string colName = Field.XPath;
933                                 bool isAttr = colName.Length > 0 && colName [0] == '@';
934                                 int index = colName.LastIndexOf (':');
935                                 if (index > 0)
936                                         colName = colName.Substring (index + 1);
937                                 else if (isAttr)
938                                         colName = colName.Substring (1);
939
940                                 colName = XmlHelper.Decode (colName);
941                                 cols [i] = colName;
942                                 isAttrSpec [i] = isAttr;
943                                 i++;
944                         }
945                         
946                         bool isPK = false;
947                         // find if there is an attribute with the constraint name
948                         // if not use the XmlSchemaConstraint's name.
949                         string constraintName = ic.Name;
950                         if (ic.UnhandledAttributes != null) {
951                                 foreach (XmlAttribute attr in ic.UnhandledAttributes) {
952                                         if (attr.NamespaceURI != XmlConstants.MsdataNamespace)
953                                                 continue;
954                                         switch (attr.LocalName) {
955                                         case XmlConstants.ConstraintName:
956                                                 constraintName = attr.Value;
957                                                 break;
958                                         case XmlConstants.PrimaryKey:
959                                                 isPK = bool.Parse(attr.Value);
960                                                 break;
961                                         }
962                                 }
963                         }
964                         reservedConstraints.Add (ic,
965                                 new ConstraintStructure (tableName, cols,
966                                         isAttrSpec, constraintName, isPK, null, false, false));
967                 }
968
969                 private void ProcessSelfIdentity (ConstraintStructure c)
970                 {
971                         // Basic concept came from XmlSchemaMapper.cs
972
973                         string tableName = c.TableName;
974                         
975                         DataTable dt = dataset.Tables [tableName];
976                         if (dt == null)
977                                 throw new DataException (String.Format ("Invalid XPath selection inside selector. Cannot find: {0}", tableName));
978
979                         DataColumn [] cols = new DataColumn [c.Columns.Length];
980                         for (int i = 0; i < cols.Length; i++) {
981                                 string colName = c.Columns [i];
982                                 bool isAttr = c.IsAttribute [i];
983                                 DataColumn col = dt.Columns [colName];
984                                 if (col == null)
985                                         throw new DataException (String.Format ("Invalid XPath selection inside field. Cannot find: {0}", tableName));
986                                 if (isAttr && col.ColumnMapping != MappingType.Attribute)
987                                         throw new DataException ("The XPath specified attribute field, but mapping type is not attribute.");
988                                 if (!isAttr && col.ColumnMapping != MappingType.Element)
989                                         throw new DataException ("The XPath specified simple element field, but mapping type is not simple element.");
990
991                                 cols [i] = dt.Columns [colName];
992                         }
993                         
994                         bool isPK = c.IsPrimaryKey;
995                         string constraintName = c.ConstraintName;
996                         dt.Constraints.Add (new UniqueConstraint (
997                                 constraintName, cols, isPK));
998                 }
999
1000                 private void ReserveRelationIdentity (XmlSchemaElement element, XmlSchemaKeyref keyref)
1001                 {
1002                         // Basic concept came from XmlSchemaMapper.cs
1003
1004                         string tableName = GetSelectorTarget (keyref.Selector.XPath);
1005
1006                         string [] cols = new string [keyref.Fields.Count];
1007                         bool [] isAttrSpec = new bool [cols.Length];
1008                         int i = 0;
1009                         foreach (XmlSchemaXPath Field in keyref.Fields) {
1010                                 string colName = Field.XPath;
1011                                 bool isAttr = colName.Length > 0 && colName [0] == '@';
1012                                 int index = colName.LastIndexOf (':');
1013                                 if (index > 0)
1014                                         colName = colName.Substring (index + 1);
1015                                 else if (isAttr)
1016                                         colName = colName.Substring (1);
1017
1018                                 colName = XmlHelper.Decode (colName);
1019                                 cols [i] = colName;
1020                                 isAttrSpec [i] = isAttr;
1021                                 i++;
1022                         }
1023                         string constraintName = keyref.Name;
1024                         bool isNested = false;
1025                         bool isConstraintOnly = false;
1026                         if (keyref.UnhandledAttributes != null) {
1027                                 foreach (XmlAttribute attr in keyref.UnhandledAttributes) {
1028                                         if (attr.NamespaceURI != XmlConstants.MsdataNamespace)
1029                                                 continue;
1030                                         switch (attr.LocalName) {
1031                                         case XmlConstants.ConstraintName:
1032                                                 constraintName = attr.Value;
1033                                                 break;
1034                                         case XmlConstants.IsNested:
1035                                                 if (attr.Value == "true")
1036                                                         isNested = true;
1037                                                 break;
1038                                         case XmlConstants.ConstraintOnly:
1039                                                 if (attr.Value == "true")
1040                                                         isConstraintOnly = true;
1041                                                 break;
1042                                         }
1043                                 }
1044                         }
1045
1046                         reservedConstraints.Add (keyref, new ConstraintStructure (
1047                                 tableName, cols, isAttrSpec, constraintName,
1048                                 false, keyref.Refer.Name, isNested, isConstraintOnly));
1049                 }
1050
1051                 private void ProcessRelationIdentity (XmlSchemaElement element, ConstraintStructure c)
1052                 {
1053                         // Basic concept came from XmlSchemaMapper.cs
1054
1055                         string tableName = c.TableName;
1056
1057                         DataColumn [] cols;
1058                         DataTable dt = dataset.Tables [tableName];
1059                         if (dt == null)
1060                                 throw new DataException (String.Format ("Invalid XPath selection inside selector. Cannot find: {0}", tableName));
1061
1062                         cols = new DataColumn [c.Columns.Length];
1063                         for (int i = 0; i < cols.Length; i++) {
1064                                 string colName = c.Columns [i];
1065                                 bool isAttr = c.IsAttribute [i];
1066                                 DataColumn col = dt.Columns [colName];
1067                                 if (isAttr && col.ColumnMapping != MappingType.Attribute)
1068                                         throw new DataException ("The XPath specified attribute field, but mapping type is not attribute.");
1069                                 if (!isAttr && col.ColumnMapping != MappingType.Element)
1070                                         throw new DataException ("The XPath specified simple element field, but mapping type is not simple element.");
1071                                 cols [i] = col;
1072                         }
1073                         string name = c.ReferName;
1074                         // get the unique constraint for the releation
1075                         UniqueConstraint uniq = FindConstraint (name, element);
1076                         // generate the FK.
1077                         ForeignKeyConstraint fkc = new ForeignKeyConstraint(c.ConstraintName, uniq.Columns, cols);
1078                         dt.Constraints.Add (fkc);
1079
1080                         if (!c.IsConstraintOnly) {
1081                                 // generate the relation.
1082                                 DataRelation rel = new DataRelation (c.ConstraintName, uniq.Columns, cols, false);
1083                                 rel.Nested = c.IsNested;
1084                                 rel.SetParentKeyConstraint (uniq);
1085                                 rel.SetChildKeyConstraint (fkc);
1086
1087                                 dataset.Relations.Add (rel);
1088                         }
1089                 }
1090
1091                 // get the unique constraint for the relation.
1092                 // name - the name of the XmlSchemaUnique element
1093                 private UniqueConstraint FindConstraint (string name, XmlSchemaElement element)
1094                 {
1095                         // Copied from XmlSchemaMapper.cs
1096
1097                         // find the element in the constraint collection.
1098                         foreach (XmlSchemaIdentityConstraint c in element.Constraints) {
1099                                 if (c is XmlSchemaKeyref)
1100                                         continue;
1101
1102                                 if (c.Name == name) {
1103                                         string tableName = GetSelectorTarget (c.Selector.XPath);
1104
1105                                         // find the table in the dataset.
1106                                         DataTable dt = dataset.Tables [tableName];
1107
1108                                         string constraintName = c.Name;
1109                                         // find if there is an attribute with the constraint name
1110                                         // if not use the XmlSchemaUnique name.
1111                                         if (c.UnhandledAttributes != null)
1112                                                 foreach (XmlAttribute attr in c.UnhandledAttributes)
1113                                                         if (attr.LocalName == "ConstraintName" && attr.NamespaceURI == XmlConstants.MsdataNamespace)
1114                                                                 constraintName = attr.Value;
1115                                         return (UniqueConstraint) dt.Constraints [constraintName];
1116                                 }
1117                         }
1118                         throw new DataException ("Target identity constraint was not found: " + name);
1119                 }
1120
1121                 private void HandleAnnotations (XmlSchemaAnnotation an, bool nested)
1122                 {
1123                         foreach (XmlSchemaObject content in an.Items) {
1124                                 XmlSchemaAppInfo ai = content as XmlSchemaAppInfo;
1125                                 if (ai != null) {
1126                                         foreach (XmlNode n in ai.Markup) {
1127                                                 XmlElement el = n as XmlElement;
1128                                                 if (el != null && el.LocalName == "Relationship" && el.NamespaceURI == XmlConstants.MsdataNamespace)
1129                                                         HandleRelationshipAnnotation (el, nested);
1130                                         }
1131                                 }
1132                         }
1133                 }
1134
1135                 private void HandleRelationshipAnnotation (XmlElement el, bool nested)
1136                 {
1137                         string name = el.GetAttribute ("name");
1138                         string ptn = el.GetAttribute ("parent", XmlConstants.MsdataNamespace);
1139                         string ctn = el.GetAttribute ("child", XmlConstants.MsdataNamespace);
1140                         string pkn = el.GetAttribute ("parentkey", XmlConstants.MsdataNamespace);
1141                         string fkn = el.GetAttribute ("childkey", XmlConstants.MsdataNamespace);
1142
1143                         RelationStructure rel = new RelationStructure ();
1144                         rel.ExplicitName = XmlHelper.Decode (name);
1145                         rel.ParentTableName = XmlHelper.Decode (ptn);
1146                         rel.ChildTableName = XmlHelper.Decode (ctn);
1147                         // ColumnNames will be decoded wherever they are used as they can
1148                         // contain 'space' separated list of column-names.
1149                         rel.ParentColumnName = pkn;
1150                         rel.ChildColumnName = fkn;
1151                         rel.IsNested = nested;
1152                         rel.CreateConstraint = false; // by default?
1153                         relations.Add (rel);
1154                 }
1155
1156                 private object GetElementDefaultValue (XmlSchemaElement elem)
1157                 {
1158                         // Unlike attribute, element cannot have a default value.
1159                         if (elem.RefName == XmlQualifiedName.Empty)
1160                                 return elem.DefaultValue;
1161                         XmlSchemaElement referenced = schema.Elements [elem.RefName] as XmlSchemaElement;
1162                         if (referenced == null) // considering missing sub components
1163                                 return null;
1164                         return referenced.DefaultValue;
1165                 }
1166
1167                 private object GetAttributeDefaultValue (XmlSchemaAttribute attr)
1168                 {
1169 #if BUGGY_MS_COMPATIBLE
1170                         if (attr == null)
1171                                 return null;
1172                         else if (attr.RefName != XmlQualifiedName.Empty) {
1173                                 XmlSchemaAttribute referenced = schema.Attributes [attr.RefName] as XmlSchemaAttribute;
1174                                 if (referenced != null)
1175                                         return referenced.DefaultValue;
1176                                 else
1177                                         return null;
1178                         }
1179                         if (attr.DefaultValue != null)
1180                                 return attr.DefaultValue;
1181                         return attr.FixedValue;
1182 #else
1183                         if (attr.DefaultValue != null)
1184                                 return attr.DefaultValue;
1185                         else if (attr.FixedValue != null)
1186                                 return attr.FixedValue;
1187                         else if (attr.RefName == XmlQualifiedName.Empty)
1188                                 return null;
1189                         XmlSchemaAttribute referenced = schema.Attributes [attr.RefName] as XmlSchemaAttribute;
1190                         if (referenced == null) // considering missing sub components
1191                                 return null;
1192                         if (referenced.DefaultValue != null)
1193                                 return referenced.DefaultValue;
1194                         return referenced.FixedValue;
1195 #endif
1196                 }
1197         }
1198 }