Welcome to mirror list, hosted at ThFree Co, Russian Federation.

XmlSchemaImporter.cs « System.Xml.Serialization « System.XML « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d687e68c70f99a3db46bcc028e1d850aeebf224a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
// 
// System.Xml.Serialization.XmlSchemaImporter
//
// Author:
//   Tim Coleman (tim@timcoleman.com)
//   Lluis Sanchez Gual (lluis@ximian.com)
//
// Copyright (C) Tim Coleman, 2002
//

//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System.Xml;
using System.Xml.Schema;
using System.Collections;

namespace System.Xml.Serialization 
{
	public class XmlSchemaImporter
#if NET_2_0
		: SchemaImporter
#endif
	{
		#region Fields

		XmlSchemas schemas;
		CodeIdentifiers typeIdentifiers;
		CodeIdentifiers elemIdentifiers = new CodeIdentifiers ();
		Hashtable mappedTypes = new Hashtable ();
		Hashtable dataMappedTypes = new Hashtable ();
		Queue pendingMaps = new Queue ();
		Hashtable sharedAnonymousTypes = new Hashtable ();
		bool encodedFormat = false;
		XmlReflectionImporter auxXmlRefImporter;
		SoapReflectionImporter auxSoapRefImporter;
		bool anyTypeImported;

#if NET_2_0
		CodeGenerationOptions options;
#endif

		static readonly XmlQualifiedName anyType = new XmlQualifiedName ("anyType",XmlSchema.Namespace);
		static readonly XmlQualifiedName arrayType = new XmlQualifiedName ("Array",XmlSerializer.EncodingNamespace);
		static readonly XmlQualifiedName arrayTypeRefName = new XmlQualifiedName ("arrayType",XmlSerializer.EncodingNamespace);
		
		const string XmlNamespace = "http://www.w3.org/XML/1998/namespace";
		
		XmlSchemaElement anyElement = null;

		class MapFixup
		{
			public XmlTypeMapping Map;
			public XmlSchemaComplexType SchemaType;
			public XmlQualifiedName TypeName;
		}

		#endregion

		#region Constructors

		public XmlSchemaImporter (XmlSchemas schemas)
		{
			this.schemas = schemas;
			typeIdentifiers = new CodeIdentifiers ();
		}

		public XmlSchemaImporter (XmlSchemas schemas, CodeIdentifiers typeIdentifiers)
			: this (schemas)
		{
			this.typeIdentifiers = typeIdentifiers;
		}
		
#if NET_2_0
		[MonoTODO]
		public XmlSchemaImporter (XmlSchemas schemas, CodeGenerationOptions options, System.CodeDom.Compiler.ICodeGenerator codeGenerator, ImportContext context)
		{
			this.schemas = schemas;
			this.options = options;
			if (context != null) {
				typeIdentifiers = context.TypeIdentifiers;
				InitSharedData (context);
			}
			else
				typeIdentifiers = new CodeIdentifiers ();
		}
		
		public XmlSchemaImporter (XmlSchemas schemas, CodeGenerationOptions options, ImportContext context)
		{
			this.schemas = schemas;
			this.options = options;
			if (context != null) {
				typeIdentifiers = context.TypeIdentifiers;
				InitSharedData (context);
			}
			else
				typeIdentifiers = new CodeIdentifiers ();
		}
		

		public XmlSchemaImporter (XmlSchemas schemas, CodeIdentifiers typeIdentifiers, CodeGenerationOptions options)
		{
			this.typeIdentifiers = typeIdentifiers;
			this.schemas = schemas;
			this.options = options;
		}
		
		void InitSharedData (ImportContext context)
		{
			if (context.ShareTypes) {
				mappedTypes = context.MappedTypes;
				dataMappedTypes = context.DataMappedTypes;
				sharedAnonymousTypes = context.SharedAnonymousTypes;
			}
		}
#endif
		
		internal bool UseEncodedFormat
		{
			get { return encodedFormat; }
			set { encodedFormat = value; }
		}

		#endregion // Constructors

		#region Methods

		public XmlMembersMapping ImportAnyType (XmlQualifiedName typeName, string elementName)
		{
			if (typeName == XmlQualifiedName.Empty)
			{
				XmlTypeMapMemberAnyElement mapMem = new XmlTypeMapMemberAnyElement ();
				mapMem.Name = typeName.Name;
				mapMem.TypeData = TypeTranslator.GetTypeData(typeof(XmlNode));
				mapMem.ElementInfo.Add (CreateElementInfo (typeName.Namespace, mapMem, typeName.Name, mapMem.TypeData, true, XmlSchemaForm.None));
				
				XmlMemberMapping[] mm = new XmlMemberMapping [1];
				mm[0] = new XmlMemberMapping (typeName.Name, typeName.Namespace, mapMem, encodedFormat);
				return new XmlMembersMapping (mm);
			}
			else
			{
				XmlSchemaComplexType stype = (XmlSchemaComplexType) schemas.Find (typeName, typeof (XmlSchemaComplexType));
				if (stype == null) 
					throw new InvalidOperationException ("Referenced type '" + typeName + "' not found");
				
				if (!CanBeAnyElement (stype))
					throw new InvalidOperationException ("The type '" + typeName + "' is not valid for a collection of any elements");
					
				ClassMap cmap = new ClassMap ();
				CodeIdentifiers classIds = new CodeIdentifiers ();
				bool isMixed = stype.IsMixed;
				ImportSequenceContent (typeName, cmap, ((XmlSchemaSequence) stype.Particle).Items, classIds, false, ref isMixed);
				XmlTypeMapMemberAnyElement mapMem = (XmlTypeMapMemberAnyElement) cmap.AllMembers[0];
				mapMem.Name = typeName.Name;
				
				XmlMemberMapping[] mm = new XmlMemberMapping [1];
				mm[0] = new XmlMemberMapping (typeName.Name, typeName.Namespace, mapMem, encodedFormat);
				return new XmlMembersMapping (mm);
			}
		}

		public XmlTypeMapping ImportDerivedTypeMapping (XmlQualifiedName name, Type baseType)
		{
			return ImportDerivedTypeMapping (name, baseType, true);
		}
		
		public XmlTypeMapping ImportDerivedTypeMapping (XmlQualifiedName name, Type baseType, bool baseTypeCanBeIndirect)
		{
			XmlQualifiedName qname;
			XmlSchemaType stype;
			
			if (encodedFormat)
			{
				qname = name;
				stype = schemas.Find (name, typeof (XmlSchemaComplexType)) as XmlSchemaComplexType;
				if (stype == null) throw new InvalidOperationException ("Schema type '" + name + "' not found or not valid");
			}
			else
			{
				if (!LocateElement (name, out qname, out stype))
					return null;
			}

			XmlTypeMapping map = GetRegisteredTypeMapping (qname);
			if (map != null)
			{
				// If the type has already been imported, make sure that the map 
				// has the requested base type
				
				SetMapBaseType (map, baseType);
				map.UpdateRoot (name);
				return map;
			}
			
			map = CreateTypeMapping (qname, SchemaTypes.Class, name);
			if (stype != null) {
				map.Documentation = GetDocumentation (stype);
				RegisterMapFixup (map, qname, (XmlSchemaComplexType)stype);
			} else {
				ClassMap cmap = new ClassMap ();
				CodeIdentifiers classIds = new CodeIdentifiers ();
				map.ObjectMap = cmap;
				AddTextMember (qname, cmap, classIds);
			}
			
			BuildPendingMaps ();
			SetMapBaseType (map, baseType);
			
			return map;
		}
		
		void SetMapBaseType (XmlTypeMapping map, Type baseType)
		{
			// This method sets the base type for a given map.
			// If the map already inherits from this type, it does nothing.
			
			// Fiirst of all, check if the map already inherits from baseType
				
			XmlTypeMapping topMap = null;
			while (map != null)
			{
				if (map.TypeData.Type == baseType)
					return;
				topMap = map;
				map = map.BaseMap;
			}
			
			// Does not have the requested base type.
			// Then, get/create a map for that base type.
			
			XmlTypeMapping baseMap = ReflectType (baseType, null);
			
			// Add this map as a derived map of the base map

			topMap.BaseMap = baseMap;
			baseMap.DerivedTypes.Add (topMap);
			baseMap.DerivedTypes.AddRange (topMap.DerivedTypes);
			
			// Now add the base type fields to all derived maps

			ClassMap baseClassMap = (ClassMap)baseMap.ObjectMap;
			
			ClassMap cmap = (ClassMap)topMap.ObjectMap;
			foreach (XmlTypeMapMember member in baseClassMap.AllMembers)
				cmap.AddMember (member);
				
			foreach (XmlTypeMapping derivedMap in topMap.DerivedTypes)
			{
				cmap = (ClassMap)derivedMap.ObjectMap;
				foreach (XmlTypeMapMember member in baseClassMap.AllMembers)
					cmap.AddMember (member);
			}
		}

		public XmlMembersMapping ImportMembersMapping (XmlQualifiedName name)
		{
			XmlSchemaElement elem = (XmlSchemaElement) schemas.Find (name, typeof (XmlSchemaElement));
			if (elem == null) throw new InvalidOperationException ("Schema element '" + name + "' not found or not valid");

			XmlSchemaComplexType stype;
			if (elem.SchemaType != null)
			{
				stype = elem.SchemaType as XmlSchemaComplexType;
			}
			else
			{
				if (elem.SchemaTypeName.IsEmpty) return null;
				object type = schemas.Find (elem.SchemaTypeName, typeof (XmlSchemaComplexType));
				if (type == null) {
					if (IsPrimitiveTypeNamespace (elem.SchemaTypeName.Namespace)) return null;
					throw new InvalidOperationException ("Schema type '" + elem.SchemaTypeName + "' not found");
				}
				stype = type as XmlSchemaComplexType;
			}
			
			if (stype == null) 
				throw new InvalidOperationException ("Schema element '" + name + "' not found or not valid");
			
			XmlMemberMapping[] mapping = ImportMembersMappingComposite (stype, name);			
			return new XmlMembersMapping (name.Name, name.Namespace, mapping);
		}
		
		public XmlMembersMapping ImportMembersMapping (XmlQualifiedName[] names)
		{
			XmlMemberMapping[] mapping = new XmlMemberMapping [names.Length];
			for (int n=0; n<names.Length; n++)
			{
				XmlSchemaElement elem = (XmlSchemaElement) schemas.Find (names[n], typeof (XmlSchemaElement));
				if (elem == null) throw new InvalidOperationException ("Schema element '" + names[n] + "' not found");
				
				XmlQualifiedName typeQName = new XmlQualifiedName ("Message", names[n].Namespace);
				XmlTypeMapping tmap;
				TypeData td = GetElementTypeData (typeQName, elem, names[n], out tmap);
				
				mapping[n] = ImportMemberMapping (elem.Name, typeQName.Namespace, elem.IsNillable, td, tmap);
			}
			BuildPendingMaps ();
			return new XmlMembersMapping (mapping);
		}
		
#if NET_2_0
		[MonoTODO]
		public XmlMembersMapping ImportMembersMapping (string name, string ns, SoapSchemaMember[] members)
		{
			throw new NotImplementedException ();
		}
		
		[MonoTODO]
		public XmlTypeMapping ImportSchemaType (XmlQualifiedName typeName)
		{
			throw new NotImplementedException ();
		}
		
		[MonoTODO]
		public XmlTypeMapping ImportSchemaType (XmlQualifiedName typeName, Type baseType)
		{
			throw new NotImplementedException ();
		}
		
		[MonoTODO]
		public XmlTypeMapping ImportSchemaType (XmlQualifiedName typeName, Type baseType, bool baseTypeCanBeIndirect)
		{
			throw new NotImplementedException ();
		}
#endif
		
		internal XmlMembersMapping ImportEncodedMembersMapping (string name, string ns, SoapSchemaMember[] members, bool hasWrapperElement)
		{
			XmlMemberMapping[] mapping = new XmlMemberMapping [members.Length];
			for (int n=0; n<members.Length; n++)
			{
				TypeData td = GetTypeData (members[n].MemberType, null);
				XmlTypeMapping tmap = GetTypeMapping (td);
				mapping[n] = ImportMemberMapping (members[n].MemberName, members[n].MemberType.Namespace, true, td, tmap);
			}
			BuildPendingMaps ();
			return new XmlMembersMapping (name, ns, hasWrapperElement, false, mapping);
		}
		
		internal XmlMembersMapping ImportEncodedMembersMapping (string name, string ns, SoapSchemaMember member)
		{
			XmlSchemaComplexType stype = schemas.Find (member.MemberType, typeof (XmlSchemaComplexType)) as XmlSchemaComplexType;
			if (stype == null) throw new InvalidOperationException ("Schema type '" + member.MemberType + "' not found or not valid");

			XmlMemberMapping[] mapping = ImportMembersMappingComposite (stype, member.MemberType);			
			return new XmlMembersMapping (name, ns, mapping);
		}
		
		XmlMemberMapping[] ImportMembersMappingComposite (XmlSchemaComplexType stype, XmlQualifiedName refer)
		{
			if (stype.Particle == null) 
				return new XmlMemberMapping [0];

			ClassMap cmap = new ClassMap ();
			
			XmlSchemaSequence seq = stype.Particle as XmlSchemaSequence;
			if (seq == null) throw new InvalidOperationException ("Schema element '" + refer + "' cannot be imported as XmlMembersMapping");

			CodeIdentifiers classIds = new CodeIdentifiers ();
			ImportParticleComplexContent (refer, cmap, seq, classIds, false);
			ImportAttributes (refer, cmap, stype.Attributes, stype.AnyAttribute, classIds);

			BuildPendingMaps ();

			int n = 0;
			XmlMemberMapping[] mapping = new XmlMemberMapping [cmap.AllMembers.Count];
			foreach (XmlTypeMapMember mapMem in cmap.AllMembers)
				mapping[n++] = new XmlMemberMapping (mapMem.Name, refer.Namespace, mapMem, encodedFormat);
				
			return mapping;
		}
		
		XmlMemberMapping ImportMemberMapping (string name, string ns, bool isNullable, TypeData type, XmlTypeMapping emap)
		{
			XmlTypeMapMemberElement mapMem;
			
			if (type.IsListType)
				mapMem = new XmlTypeMapMemberList ();
			else
				mapMem = new XmlTypeMapMemberElement ();
			
			mapMem.Name = name;
			mapMem.TypeData = type;
			mapMem.ElementInfo.Add (CreateElementInfo (ns, mapMem, name, type, isNullable, XmlSchemaForm.None, emap));
			return new XmlMemberMapping (name, ns, mapMem, encodedFormat);
		}
		
		[MonoTODO]
		public XmlMembersMapping ImportMembersMapping (XmlQualifiedName[] names, Type baseType, bool baseTypeCanBeIndirect)
		{
			throw new NotImplementedException ();
		}

		public XmlTypeMapping ImportTypeMapping (XmlQualifiedName name)
		{
			XmlQualifiedName qname;
			XmlSchemaType stype;
			if (!LocateElement (name, out qname, out stype)) return null;
			
			if (stype == null) {
				// Importing a primitive type
				TypeData td = TypeTranslator.GetPrimitiveTypeData (qname.Name);
				return ReflectType (td.Type, name.Namespace);
			}
			
			XmlTypeMapping map = GetRegisteredTypeMapping (qname);
			if (map != null) return map;
			
			map = CreateTypeMapping (qname, SchemaTypes.Class, name);
			map.Documentation = GetDocumentation (stype);
			RegisterMapFixup (map, qname, (XmlSchemaComplexType)stype);
			
			BuildPendingMaps ();
			return map;
		}

		bool LocateElement (XmlQualifiedName name, out XmlQualifiedName qname, out XmlSchemaType stype)
		{
			qname = null;
			stype = null;
			
			XmlSchemaElement elem = (XmlSchemaElement) schemas.Find (name, typeof (XmlSchemaElement));
			if (elem == null) return false;

			// The root element must be an element with complex type

			if (elem.SchemaType != null)
			{
				stype = elem.SchemaType;
				qname = name;
			}
			else
			{
				if (elem.SchemaTypeName.IsEmpty) return false;
				
				object type = schemas.Find (elem.SchemaTypeName, typeof (XmlSchemaComplexType));
				if (type == null) type = schemas.Find (elem.SchemaTypeName, typeof (XmlSchemaSimpleType));
				if (type == null) {
					if (IsPrimitiveTypeNamespace (elem.SchemaTypeName.Namespace)) {
						qname = elem.SchemaTypeName;
						return true;
					}
					throw new InvalidOperationException ("Schema type '" + elem.SchemaTypeName + "' not found");
				}
				stype = (XmlSchemaType) type;
				qname = stype.QualifiedName;
				
				XmlSchemaType btype = stype.BaseSchemaType as XmlSchemaType;
				if (btype != null && btype.QualifiedName == elem.SchemaTypeName)
					throw new InvalidOperationException ("Cannot import schema for type '" + elem.SchemaTypeName.Name + "' from namespace '" + elem.SchemaTypeName.Namespace + "'. Redefine not supported");
			}

			if (stype is XmlSchemaSimpleType) return false;
			return true;
		}

		XmlTypeMapping ImportType (XmlQualifiedName name, XmlQualifiedName root, bool throwOnError)
		{
			XmlTypeMapping map = GetRegisteredTypeMapping (name);
			if (map != null) {
				map.UpdateRoot (root);
				return map;
			}

			XmlSchemaType type = (XmlSchemaType) schemas.Find (name, typeof (XmlSchemaComplexType));
			if (type == null) type = (XmlSchemaType) schemas.Find (name, typeof (XmlSchemaSimpleType));
			
			if (type == null) 
			{
				if (throwOnError) {
					if (name.Namespace == XmlSerializer.EncodingNamespace)
						throw new InvalidOperationException ("Referenced type '" + name + "' valid only for encoded SOAP.");
					else
						throw new InvalidOperationException ("Referenced type '" + name + "' not found.");
				} else
					return null;
			}

			return ImportType (name, type, root);
		}

		XmlTypeMapping ImportClass (XmlQualifiedName name)
		{
			XmlTypeMapping map = ImportType (name, null, true);
			if (map.TypeData.SchemaType == SchemaTypes.Class) return map;
			XmlSchemaComplexType stype = schemas.Find (name, typeof (XmlSchemaComplexType)) as XmlSchemaComplexType;
			return CreateClassMap (name, stype, new XmlQualifiedName (map.ElementName, map.Namespace));
		}
		
		XmlTypeMapping ImportType (XmlQualifiedName name, XmlSchemaType stype, XmlQualifiedName root)
		{
			XmlTypeMapping map = GetRegisteredTypeMapping (name);
			if (map != null) {
				XmlSchemaComplexType ct = stype as XmlSchemaComplexType;
				if (map.TypeData.SchemaType != SchemaTypes.Class || ct == null || !CanBeArray (name, ct)) {
					map.UpdateRoot (root);
					return map;
				}
					
				// The map was initially imported as a class, but it turns out that it is an
				// array. It has to be imported now as array.
			}
			
			if (stype is XmlSchemaComplexType)
				return ImportClassComplexType (name, (XmlSchemaComplexType) stype, root);
			else if (stype is XmlSchemaSimpleType)
				return ImportClassSimpleType (name, (XmlSchemaSimpleType) stype, root);

			throw new NotSupportedException ("Schema type not supported: " + stype.GetType ());
		}

		XmlTypeMapping ImportClassComplexType (XmlQualifiedName typeQName, XmlSchemaComplexType stype, XmlQualifiedName root)
		{
			// The need for fixups: If the complex type is an array, then to get the type of the
			// array we need first to get the type of the items of the array.
			// But if one of the item types or its children has a referece to this type array,
			// then we enter in an infinite loop. This does not happen with class types because
			// the class map is registered before parsing the children. We can't do the same
			// with the array type because to register the array map we need the type of the array.

			Type anyType = GetAnyElementType (stype);
			if (anyType != null)
				return GetTypeMapping (TypeTranslator.GetTypeData(anyType));
				
			if (CanBeArray (typeQName, stype))
			{
				TypeData typeData;
				ListMap listMap = BuildArrayMap (typeQName, stype, out typeData);
				if (listMap != null)
				{
					XmlTypeMapping map = CreateArrayTypeMapping (typeQName, typeData);
					map.ObjectMap = listMap;
					return map;
				}

				// After all, it is not an array. Create a class map then.
			}
			else if (CanBeIXmlSerializable (stype))
			{
				return ImportXmlSerializableMapping (typeQName.Namespace);
			}

			// Register the map right now but do not build it,
			// This will avoid loops.

			return CreateClassMap (typeQName, stype, root);
		}
		
		XmlTypeMapping CreateClassMap (XmlQualifiedName typeQName, XmlSchemaComplexType stype, XmlQualifiedName root)
		{
			XmlTypeMapping map = CreateTypeMapping (typeQName, SchemaTypes.Class, root);
			map.Documentation = GetDocumentation (stype);
			RegisterMapFixup (map, typeQName, stype);
			return map;
		}

		void RegisterMapFixup (XmlTypeMapping map, XmlQualifiedName typeQName, XmlSchemaComplexType stype)
		{
			MapFixup fixup = new MapFixup ();
			fixup.Map = map;
			fixup.SchemaType = stype;
			fixup.TypeName = typeQName;
			pendingMaps.Enqueue (fixup);
		}

		void BuildPendingMaps ()
		{
			while (pendingMaps.Count > 0) {
				MapFixup fixup  = (MapFixup) pendingMaps.Dequeue ();
				if (fixup.Map.ObjectMap == null) {
					BuildClassMap (fixup.Map, fixup.TypeName, fixup.SchemaType);
					if (fixup.Map.ObjectMap == null) pendingMaps.Enqueue (fixup);
				}
			}
		}

		void BuildPendingMap (XmlTypeMapping map)
		{
			if (map.ObjectMap != null) return;

			foreach (MapFixup fixup in pendingMaps)
			{
				if (fixup.Map == map) {
					BuildClassMap (fixup.Map, fixup.TypeName, fixup.SchemaType);
					return;
				}
			}
			throw new InvalidOperationException ("Can't complete map of type " + map.XmlType + " : " + map.Namespace);
		}

		void BuildClassMap (XmlTypeMapping map, XmlQualifiedName typeQName, XmlSchemaComplexType stype)
		{
			CodeIdentifiers classIds = new CodeIdentifiers();
			classIds.AddReserved (map.TypeData.TypeName);

			ClassMap cmap = new ClassMap ();
			map.ObjectMap = cmap;
			bool isMixed = stype.IsMixed;

			if (stype.Particle != null)
				ImportParticleComplexContent (typeQName, cmap, stype.Particle, classIds, isMixed);
			else
			{
				if (stype.ContentModel is XmlSchemaSimpleContent) {
					ImportSimpleContent (typeQName, map, (XmlSchemaSimpleContent)stype.ContentModel, classIds, isMixed);
				}
				else if (stype.ContentModel is XmlSchemaComplexContent) {
					ImportComplexContent (typeQName, map, (XmlSchemaComplexContent)stype.ContentModel, classIds, isMixed);
				}
			}

			ImportAttributes (typeQName, cmap, stype.Attributes, stype.AnyAttribute, classIds);
			ImportExtensionTypes (typeQName);

			if (isMixed) AddTextMember (typeQName, cmap, classIds);
			
			AddObjectDerivedMap (map);
		}
		
		void ImportAttributes (XmlQualifiedName typeQName, ClassMap cmap, XmlSchemaObjectCollection atts, XmlSchemaAnyAttribute anyat, CodeIdentifiers classIds)
		{
			if (anyat != null)
			{
    			XmlTypeMapMemberAnyAttribute member = new XmlTypeMapMemberAnyAttribute ();
				member.Name = classIds.AddUnique ("AnyAttribute", member);
				member.TypeData = TypeTranslator.GetTypeData (typeof(XmlAttribute[]));
				cmap.AddMember (member);
			}
			
			foreach (XmlSchemaObject at in atts)
			{
				if (at is XmlSchemaAttribute)
				{
					string ns;
					XmlSchemaAttribute attr = (XmlSchemaAttribute)at;
					XmlSchemaAttribute refAttr = GetRefAttribute (typeQName, attr, out ns);
					XmlTypeMapMemberAttribute member = new XmlTypeMapMemberAttribute ();
					member.Name = classIds.AddUnique (CodeIdentifier.MakeValid (refAttr.Name), member);
					member.Documentation = GetDocumentation (attr);
					member.AttributeName = refAttr.Name;
					member.Namespace = ns;
					member.Form = refAttr.Form;
					member.TypeData = GetAttributeTypeData (typeQName, attr);
					
					if (refAttr.DefaultValue != null) 
						member.DefaultValue = ImportDefaultValue (member.TypeData, refAttr.DefaultValue);
					else if (member.TypeData.IsValueType)
						member.IsOptionalValueType = (refAttr.ValidatedUse != XmlSchemaUse.Required);
						
					if (member.TypeData.IsComplexType)
						member.MappedType = GetTypeMapping (member.TypeData);
					cmap.AddMember (member);
				}
				else if (at is XmlSchemaAttributeGroupRef)
				{
					XmlSchemaAttributeGroupRef gref = (XmlSchemaAttributeGroupRef)at;
					XmlSchemaAttributeGroup grp = FindRefAttributeGroup (gref.RefName);
					ImportAttributes (typeQName, cmap, grp.Attributes, grp.AnyAttribute, classIds);
				}
			}
		}

		ListMap BuildArrayMap (XmlQualifiedName typeQName, XmlSchemaComplexType stype, out TypeData arrayTypeData)
		{
			if (encodedFormat)
			{
				XmlSchemaComplexContent content = stype.ContentModel as XmlSchemaComplexContent;
				XmlSchemaComplexContentRestriction rest = content.Content as XmlSchemaComplexContentRestriction;
				XmlSchemaAttribute arrayTypeAt = FindArrayAttribute (rest.Attributes);
				
				if (arrayTypeAt != null)
				{
					XmlAttribute[] uatts = arrayTypeAt.UnhandledAttributes;
					if (uatts == null || uatts.Length == 0) throw new InvalidOperationException ("arrayType attribute not specified in array declaration: " + typeQName);
					
					XmlAttribute xat = null;
					foreach (XmlAttribute at in uatts)
						if (at.LocalName == "arrayType" && at.NamespaceURI == XmlSerializer.WsdlNamespace)
							{ xat = at; break; }
					
					if (xat == null) 
						throw new InvalidOperationException ("arrayType attribute not specified in array declaration: " + typeQName);
	
					string name, ns, dims;
					TypeTranslator.ParseArrayType (xat.Value, out name, out ns, out dims);
					return BuildEncodedArrayMap (name + dims, ns, out arrayTypeData);
				}
				else
				{
					XmlSchemaElement elem = null;
					XmlSchemaSequence seq = rest.Particle as XmlSchemaSequence;
					if (seq != null && seq.Items.Count == 1) 
						elem = seq.Items[0] as XmlSchemaElement;
					else {
						XmlSchemaAll all = rest.Particle as XmlSchemaAll;
						if (all != null && all.Items.Count == 1)
							elem = all.Items[0] as XmlSchemaElement;
					}
					if (elem == null)
						throw new InvalidOperationException ("Unknown array format");
						
					return BuildEncodedArrayMap (elem.SchemaTypeName.Name + "[]", elem.SchemaTypeName.Namespace, out arrayTypeData);
				}
			}
			else
			{
				ClassMap cmap = new ClassMap ();
				CodeIdentifiers classIds = new CodeIdentifiers();
				ImportParticleComplexContent (typeQName, cmap, stype.Particle, classIds, stype.IsMixed);

				XmlTypeMapMemberFlatList list = (cmap.AllMembers.Count == 1) ? cmap.AllMembers[0] as XmlTypeMapMemberFlatList : null;
				if (list != null && list.ChoiceMember == null)
				{
					arrayTypeData = list.TypeData;
					return list.ListMap;
				}
				else
				{
					arrayTypeData = null;
					return null;
				}
			}
		}
		
		ListMap BuildEncodedArrayMap (string type, string ns, out TypeData arrayTypeData)
		{
			ListMap map = new ListMap ();
			
			int i = type.LastIndexOf ("[");
			if (i == -1) throw new InvalidOperationException ("Invalid arrayType value: " + type);
			if (type.IndexOf (",",i) != -1) throw new InvalidOperationException ("Multidimensional arrays are not supported");
			
			string itemType = type.Substring (0,i);
			
			TypeData itemTypeData;
			if (itemType.IndexOf ("[") != -1) 
			{
				ListMap innerListMap = BuildEncodedArrayMap (itemType, ns, out itemTypeData);
				
				int dims = itemType.Split ('[').Length - 1;
				string name = TypeTranslator.GetArrayName (type, dims);
				XmlQualifiedName qname = new XmlQualifiedName (name, ns);
				XmlTypeMapping tmap = CreateArrayTypeMapping (qname, itemTypeData);
				tmap.ObjectMap = innerListMap;
			}
			else
			{
				itemTypeData = GetTypeData (new XmlQualifiedName (itemType, ns), null);
			}
			
			arrayTypeData = itemTypeData.ListTypeData;
			
			map.ItemInfo = new XmlTypeMapElementInfoList();
			map.ItemInfo.Add (CreateElementInfo ("", null, "Item", itemTypeData, true, XmlSchemaForm.None));
			return map;
		}
		
		XmlSchemaAttribute FindArrayAttribute (XmlSchemaObjectCollection atts)
		{
			foreach (object ob in atts)
			{
				XmlSchemaAttribute att = ob as XmlSchemaAttribute;
				if (att != null && att.RefName == arrayTypeRefName) return att;
				
				XmlSchemaAttributeGroupRef gref = ob as XmlSchemaAttributeGroupRef;
				if (gref != null)
				{
					XmlSchemaAttributeGroup grp = FindRefAttributeGroup (gref.RefName);
					att = FindArrayAttribute (grp.Attributes);
					if (att != null) return att;
				}
			}
			return null;
		}

		void ImportParticleComplexContent (XmlQualifiedName typeQName, ClassMap cmap, XmlSchemaParticle particle, CodeIdentifiers classIds, bool isMixed)
		{
			ImportParticleContent (typeQName, cmap, particle, classIds, false, ref isMixed);
			if (isMixed) AddTextMember (typeQName, cmap, classIds);
		}
		
		void AddTextMember (XmlQualifiedName typeQName, ClassMap cmap, CodeIdentifiers classIds)
		{
			if (cmap.XmlTextCollector == null)
			{
				XmlTypeMapMemberFlatList member = new XmlTypeMapMemberFlatList ();
				member.Name = classIds.AddUnique ("Text", member);
				member.TypeData = TypeTranslator.GetTypeData (typeof(string[]));
				member.ElementInfo.Add (CreateTextElementInfo (typeQName.Namespace, member, member.TypeData.ListItemTypeData));
				member.IsXmlTextCollector = true;
				member.ListMap = new ListMap ();
				member.ListMap.ItemInfo = member.ElementInfo;
				cmap.AddMember (member);
			}
		}
		
		void ImportParticleContent (XmlQualifiedName typeQName, ClassMap cmap, XmlSchemaParticle particle, CodeIdentifiers classIds, bool multiValue, ref bool isMixed)
		{
			if (particle == null) return;
			
			if (particle is XmlSchemaGroupRef)
				particle = GetRefGroupParticle ((XmlSchemaGroupRef)particle);

			if (particle.MaxOccurs > 1) multiValue = true;
			
			if (particle is XmlSchemaSequence) {
				ImportSequenceContent (typeQName, cmap, ((XmlSchemaSequence)particle).Items, classIds, multiValue, ref isMixed);
			}
			else if (particle is XmlSchemaChoice) {
				if (((XmlSchemaChoice)particle).Items.Count == 1)
					ImportSequenceContent (typeQName, cmap, ((XmlSchemaChoice)particle).Items, classIds, multiValue, ref isMixed);
				else
					ImportChoiceContent (typeQName, cmap, (XmlSchemaChoice)particle, classIds, multiValue);
			}
			else if (particle is XmlSchemaAll) {
				ImportSequenceContent (typeQName, cmap, ((XmlSchemaAll)particle).Items, classIds, multiValue, ref isMixed);
			}
		}

		void ImportSequenceContent (XmlQualifiedName typeQName, ClassMap cmap, XmlSchemaObjectCollection items, CodeIdentifiers classIds, bool multiValue, ref bool isMixed)
		{
			foreach (XmlSchemaObject item in items)
			{
				if (item is XmlSchemaElement)
				{
					string ns;
					XmlSchemaElement elem = (XmlSchemaElement) item;
					XmlTypeMapping emap;
					TypeData typeData = GetElementTypeData (typeQName, elem, null, out emap);
					XmlSchemaElement refElem = GetRefElement (typeQName, elem, out ns);

					if (elem.MaxOccurs == 1 && !multiValue)
					{
						XmlTypeMapMemberElement member = null;
						if (typeData.SchemaType != SchemaTypes.Array)
						{
							member = new XmlTypeMapMemberElement ();
							if (refElem.DefaultValue != null) member.DefaultValue = ImportDefaultValue (typeData, refElem.DefaultValue);
						}
						else if (GetTypeMapping (typeData).IsSimpleType)
						{
							// It is a simple list (space separated list).
							// Since this is not supported, map as a single item value
							// TODO: improve this
							member = new XmlTypeMapMemberElement ();
							typeData = typeData.ListItemTypeData;
						}
						else
							member = new XmlTypeMapMemberList ();

						if (elem.MinOccurs == 0 && typeData.IsValueType)
							member.IsOptionalValueType = true;

						member.Name = classIds.AddUnique(CodeIdentifier.MakeValid(refElem.Name), member);
						member.Documentation = GetDocumentation (elem);
						member.TypeData = typeData;
						member.ElementInfo.Add (CreateElementInfo (ns, member, refElem.Name, typeData, refElem.IsNillable, refElem.Form, emap));
						cmap.AddMember (member);
					}
					else
					{
						XmlTypeMapMemberFlatList member = new XmlTypeMapMemberFlatList ();
						member.ListMap = new ListMap ();
						member.Name = classIds.AddUnique(CodeIdentifier.MakeValid(refElem.Name), member);
						member.Documentation = GetDocumentation (elem);
						member.TypeData = typeData.ListTypeData;
						member.ElementInfo.Add (CreateElementInfo (ns, member, refElem.Name, typeData, refElem.IsNillable, refElem.Form, emap));
						member.ListMap.ItemInfo = member.ElementInfo;
						cmap.AddMember (member);
					}
				}
				else if (item is XmlSchemaAny)
				{
					XmlSchemaAny elem = (XmlSchemaAny) item;
					XmlTypeMapMemberAnyElement member = new XmlTypeMapMemberAnyElement ();
					member.Name = classIds.AddUnique ("Any", member);
					member.Documentation = GetDocumentation (elem);
					
					Type ctype;
					if (elem.MaxOccurs != 1 || multiValue)
						ctype = isMixed ? typeof(XmlNode[]) : typeof(XmlElement[]);
					else
						ctype = isMixed ? typeof(XmlNode) : typeof(XmlElement);

					member.TypeData = TypeTranslator.GetTypeData (ctype);
					XmlTypeMapElementInfo einfo = new XmlTypeMapElementInfo (member, member.TypeData);
					einfo.IsUnnamedAnyElement = true;
					member.ElementInfo.Add (einfo);

					if (isMixed)
					{
						einfo = CreateTextElementInfo (typeQName.Namespace, member, member.TypeData);
						member.ElementInfo.Add (einfo);
						member.IsXmlTextCollector = true;
						isMixed = false;	//Allow only one XmlTextAttribute
					}
					
					cmap.AddMember (member);
				}
				else if (item is XmlSchemaParticle) {
					ImportParticleContent (typeQName, cmap, (XmlSchemaParticle)item, classIds, multiValue, ref isMixed);
				}
			}
		}
		
		object ImportDefaultValue (TypeData typeData, string value)
		{
			if (typeData.SchemaType == SchemaTypes.Enum) {
				XmlTypeMapping map = GetTypeMapping (typeData);
				EnumMap emap = (EnumMap) map.ObjectMap;
				string res = emap.GetEnumName (value);
				if (res == null) throw new InvalidOperationException ("'" + value + "' is not a valid enumeration value");
				return res;
			} else
				return XmlCustomFormatter.FromXmlString (typeData, value);
		}
		
		void ImportChoiceContent (XmlQualifiedName typeQName, ClassMap cmap, XmlSchemaChoice choice, CodeIdentifiers classIds, bool multiValue)
		{
			XmlTypeMapElementInfoList choices = new XmlTypeMapElementInfoList ();
			multiValue = ImportChoices (typeQName, null, choices, choice.Items) || multiValue;
			if (choices.Count == 0) return;

			if (choice.MaxOccurs > 1) multiValue = true;

			XmlTypeMapMemberElement member;
			if (multiValue)
			{
				member = new XmlTypeMapMemberFlatList ();
				member.Name = classIds.AddUnique ("Items", member);
				ListMap listMap = new ListMap ();
				listMap.ItemInfo = choices;
				((XmlTypeMapMemberFlatList)member).ListMap = listMap;
			}
			else
			{
				member = new XmlTypeMapMemberElement ();
				member.Name = classIds.AddUnique ("Item", member);
			}
			
			// If all choices have the same type, use that type for the member.
			// If not use System.Object.
			// If there are at least two choices with the same type, use a choice
			// identifier attribute

			TypeData typeData = null;
			bool twoEqual = false;
			bool allEqual = true;
			Hashtable types = new Hashtable ();

			for (int n = choices.Count - 1; n >= 0; n--)
			{
				XmlTypeMapElementInfo einfo = (XmlTypeMapElementInfo) choices [n];
				
				// In some complex schemas, we may end up with several options
				// with the same name. It is better to ignore the extra options
				// than to crash. It's the best we can do, and btw it works
				// better than in MS.NET.
				
				if (cmap.GetElement (einfo.ElementName, einfo.Namespace) != null ||
					choices.IndexOfElement (einfo.ElementName, einfo.Namespace) != n)
				{
					choices.RemoveAt (n);
					continue;
				}
					
				if (types.ContainsKey (einfo.TypeData)) twoEqual = true;
				else types.Add (einfo.TypeData, einfo);

				TypeData choiceType = einfo.TypeData;
				if (choiceType.SchemaType == SchemaTypes.Class)
				{
					// When comparing class types, use the most generic class in the
					// inheritance hierarchy

					XmlTypeMapping choiceMap = GetTypeMapping (choiceType);
					BuildPendingMap (choiceMap);
					while (choiceMap.BaseMap != null) {
						choiceMap = choiceMap.BaseMap;
						BuildPendingMap (choiceMap);
						choiceType = choiceMap.TypeData;
					}
				}
				
				if (typeData == null) typeData = choiceType;
				else if (typeData != choiceType) allEqual = false;
			}

			if (!allEqual)
				typeData = TypeTranslator.GetTypeData (typeof(object));

			if (twoEqual)
			{
				// Create the choice member
				XmlTypeMapMemberElement choiceMember = new XmlTypeMapMemberElement ();
				choiceMember.Ignore = true;
				choiceMember.Name = classIds.AddUnique (member.Name + "ElementName", choiceMember);
				member.ChoiceMember = choiceMember.Name;

				// Create the choice enum
				XmlTypeMapping enumMap = CreateTypeMapping (new XmlQualifiedName (member.Name + "ChoiceType", typeQName.Namespace), SchemaTypes.Enum, null);
				enumMap.IncludeInSchema = false;

				CodeIdentifiers codeIdents = new CodeIdentifiers ();
				EnumMap.EnumMapMember[] members = new EnumMap.EnumMapMember [choices.Count];
				for (int n=0; n<choices.Count; n++)
				{
					XmlTypeMapElementInfo it =(XmlTypeMapElementInfo) choices[n];
					bool extraNs = (it.Namespace != null && it.Namespace != "" && it.Namespace != typeQName.Namespace);
					string xmlName = extraNs ? it.Namespace + ":" + it.ElementName : it.ElementName;
					string enumName = codeIdents.AddUnique (CodeIdentifier.MakeValid (it.ElementName), it);
					members [n] = new EnumMap.EnumMapMember (xmlName, enumName);
				}
				enumMap.ObjectMap = new EnumMap (members, false);

				choiceMember.TypeData = multiValue ? enumMap.TypeData.ListTypeData : enumMap.TypeData;
				choiceMember.ElementInfo.Add (CreateElementInfo (typeQName.Namespace, choiceMember, choiceMember.Name, choiceMember.TypeData, false, XmlSchemaForm.None));
				cmap.AddMember (choiceMember);
			}

			if (multiValue)
				typeData = typeData.ListTypeData;

			member.ElementInfo = choices;
			member.Documentation = GetDocumentation (choice);
			member.TypeData = typeData;
			cmap.AddMember (member);
		}

		bool ImportChoices (XmlQualifiedName typeQName, XmlTypeMapMember member, XmlTypeMapElementInfoList choices, XmlSchemaObjectCollection items)
		{
			bool multiValue = false;
			foreach (XmlSchemaObject titem in items)
			{
				XmlSchemaObject item = titem;
				if (item is XmlSchemaGroupRef)
					item = GetRefGroupParticle ((XmlSchemaGroupRef)item);

				if (item is XmlSchemaElement)
				{
					string ns;
					XmlSchemaElement elem = (XmlSchemaElement) item;
					XmlTypeMapping emap;
					TypeData typeData = GetElementTypeData (typeQName, elem, null, out emap);
					XmlSchemaElement refElem = GetRefElement (typeQName, elem, out ns);
					choices.Add (CreateElementInfo (ns, member, refElem.Name, typeData, refElem.IsNillable, refElem.Form, emap));
					if (elem.MaxOccurs > 1) multiValue = true;
				}
				else if (item is XmlSchemaAny)
				{
					XmlTypeMapElementInfo einfo = new XmlTypeMapElementInfo (member, TypeTranslator.GetTypeData(typeof(XmlElement)));
					einfo.IsUnnamedAnyElement = true;
					choices.Add (einfo);
				}
				else if (item is XmlSchemaChoice) {
					multiValue = ImportChoices (typeQName, member, choices, ((XmlSchemaChoice)item).Items) || multiValue;
				}
				else if (item is XmlSchemaSequence) {
					multiValue = ImportChoices (typeQName, member, choices, ((XmlSchemaSequence)item).Items) || multiValue;
				}
			}
			return multiValue;
		}

		void ImportSimpleContent (XmlQualifiedName typeQName, XmlTypeMapping map, XmlSchemaSimpleContent content, CodeIdentifiers classIds, bool isMixed)
		{
			XmlSchemaSimpleContentExtension ext = content.Content as XmlSchemaSimpleContentExtension;
			ClassMap cmap = (ClassMap)map.ObjectMap;
			XmlQualifiedName qname = GetContentBaseType (content.Content);
			TypeData simpleType = null;
			
			if (!IsPrimitiveTypeNamespace (qname.Namespace))
			{
				// Add base map members to this map
	
				XmlTypeMapping baseMap = ImportType (qname, null, true);
				BuildPendingMap (baseMap);
				
				if (baseMap.IsSimpleType) {
					simpleType = baseMap.TypeData;
				} else {
					ClassMap baseClassMap = (ClassMap)baseMap.ObjectMap;
		
					foreach (XmlTypeMapMember member in baseClassMap.AllMembers)
						cmap.AddMember (member);
		
					map.BaseMap = baseMap;
					baseMap.DerivedTypes.Add (map);
				}
			}
			else
				simpleType = FindBuiltInType (qname);
				
			if (simpleType != null) {
				XmlTypeMapMemberElement member = new XmlTypeMapMemberElement ();
				member.Name = classIds.AddUnique("Value", member);
				member.TypeData = simpleType;
				member.ElementInfo.Add (CreateTextElementInfo (typeQName.Namespace, member, member.TypeData));
				member.IsXmlTextCollector = true;
				cmap.AddMember (member);
			}
			
			if (ext != null)
				ImportAttributes (typeQName, cmap, ext.Attributes, ext.AnyAttribute, classIds);
		}

		TypeData FindBuiltInType (XmlQualifiedName qname)
		{
			XmlSchemaComplexType ct = (XmlSchemaComplexType) schemas.Find (qname, typeof(XmlSchemaComplexType));
			if (ct != null)
			{
				XmlSchemaSimpleContent sc = ct.ContentModel as XmlSchemaSimpleContent;
				if (sc == null) throw new InvalidOperationException ("Invalid schema");
				return FindBuiltInType (GetContentBaseType (sc.Content));
			}
			
			XmlSchemaSimpleType st = (XmlSchemaSimpleType) schemas.Find (qname, typeof(XmlSchemaSimpleType));
			if (st != null)
				return FindBuiltInType (qname, st);

			if (IsPrimitiveTypeNamespace (qname.Namespace))
				return TypeTranslator.GetPrimitiveTypeData (qname.Name);

			throw new InvalidOperationException ("Definition of type '" + qname + "' not found");
		}

		TypeData FindBuiltInType (XmlQualifiedName qname, XmlSchemaSimpleType st)
		{
			if (CanBeEnum (st))
				return ImportType (qname, null, true).TypeData;

			if (st.Content is XmlSchemaSimpleTypeRestriction) {
				XmlSchemaSimpleTypeRestriction rest = (XmlSchemaSimpleTypeRestriction) st.Content;
				XmlQualifiedName bn = GetContentBaseType (rest);
				if (bn == XmlQualifiedName.Empty && rest.BaseType != null)
					return FindBuiltInType (qname, rest.BaseType);
				else
					return FindBuiltInType (bn);
			}
			else if (st.Content is XmlSchemaSimpleTypeList) {
				return FindBuiltInType (GetContentBaseType (st.Content)).ListTypeData;
			}
			else if (st.Content is XmlSchemaSimpleTypeUnion)
			{
				// Check if all types of the union are equal. If not, then will use anyType.
				XmlSchemaSimpleTypeUnion uni = (XmlSchemaSimpleTypeUnion) st.Content;
				TypeData utype = null;

				// Anonymous types are unique
				if (uni.BaseTypes.Count != 0 && uni.MemberTypes.Length != 0)
					return FindBuiltInType (anyType);

				foreach (XmlQualifiedName mt in uni.MemberTypes)
				{
					TypeData qn = FindBuiltInType (mt);
					if (utype != null && qn != utype) return FindBuiltInType (anyType);
					else utype = qn;
				}
				return utype;
			}
			else
				return null;
		}

		XmlQualifiedName GetContentBaseType (XmlSchemaObject ob)
		{
			if (ob is XmlSchemaSimpleContentExtension)
				return ((XmlSchemaSimpleContentExtension)ob).BaseTypeName;
			else if (ob is XmlSchemaSimpleContentRestriction)
				return ((XmlSchemaSimpleContentRestriction)ob).BaseTypeName;
			else if (ob is XmlSchemaSimpleTypeRestriction)
				return ((XmlSchemaSimpleTypeRestriction)ob).BaseTypeName;
			else if (ob is XmlSchemaSimpleTypeList)
				return ((XmlSchemaSimpleTypeList)ob).ItemTypeName;
			else
				return null;
		}

		void ImportComplexContent (XmlQualifiedName typeQName, XmlTypeMapping map, XmlSchemaComplexContent content, CodeIdentifiers classIds, bool isMixed)
		{
			ClassMap cmap = (ClassMap)map.ObjectMap;
			XmlQualifiedName qname;

			XmlSchemaComplexContentExtension ext = content.Content as XmlSchemaComplexContentExtension;
			if (ext != null) qname = ext.BaseTypeName;
			else qname = ((XmlSchemaComplexContentRestriction)content.Content).BaseTypeName;
			
			if (qname == typeQName)
				throw new InvalidOperationException ("Cannot import schema for type '" + typeQName.Name + "' from namespace '" + typeQName.Namespace + "'. Redefine not supported");
			
			// Add base map members to this map

			XmlTypeMapping baseMap = ImportClass (qname);
			BuildPendingMap (baseMap);
			ClassMap baseClassMap = (ClassMap)baseMap.ObjectMap;

			foreach (XmlTypeMapMember member in baseClassMap.AllMembers)
				cmap.AddMember (member);

			if (baseClassMap.XmlTextCollector != null) isMixed = false;
			else if (content.IsMixed) isMixed = true;

			map.BaseMap = baseMap;
			baseMap.DerivedTypes.Add (map);

			if (ext != null) {
				// Add the members of this map
				ImportParticleComplexContent (typeQName, cmap, ext.Particle, classIds, isMixed);
				ImportAttributes (typeQName, cmap, ext.Attributes, ext.AnyAttribute, classIds);
			}
			else {
				if (isMixed) ImportParticleComplexContent (typeQName, cmap, null, classIds, true);
			}
		}
		
		void ImportExtensionTypes (XmlQualifiedName qname)
		{
			foreach (XmlSchema schema in schemas) {
				foreach (XmlSchemaObject sob in schema.Items) 
				{
					XmlSchemaComplexType sct = sob as XmlSchemaComplexType;
					if (sct != null && sct.ContentModel is XmlSchemaComplexContent) {
						XmlQualifiedName exqname;
						XmlSchemaComplexContentExtension ext = sct.ContentModel.Content as XmlSchemaComplexContentExtension;
						if (ext != null) exqname = ext.BaseTypeName;
						else exqname = ((XmlSchemaComplexContentRestriction)sct.ContentModel.Content).BaseTypeName;
						if (exqname == qname)
							ImportType (new XmlQualifiedName (sct.Name, schema.TargetNamespace), sct, null);
					}
				}
			}					
		}

		XmlTypeMapping ImportClassSimpleType (XmlQualifiedName typeQName, XmlSchemaSimpleType stype, XmlQualifiedName root)
		{
			if (CanBeEnum (stype))
			{
				// Create an enum map

				CodeIdentifiers codeIdents = new CodeIdentifiers ();
				XmlTypeMapping enumMap = CreateTypeMapping (typeQName, SchemaTypes.Enum, null);
				enumMap.Documentation = GetDocumentation (stype);
				
				bool isFlags = false;
				if (stype.Content is XmlSchemaSimpleTypeList) {
					stype = ((XmlSchemaSimpleTypeList)stype.Content).ItemType;
					isFlags = true;
				}
				XmlSchemaSimpleTypeRestriction rest = (XmlSchemaSimpleTypeRestriction)stype.Content;

				codeIdents.AddReserved (enumMap.TypeData.TypeName);

				EnumMap.EnumMapMember[] members = new EnumMap.EnumMapMember [rest.Facets.Count];
				for (int n=0; n<rest.Facets.Count; n++)
				{
					XmlSchemaEnumerationFacet enu = (XmlSchemaEnumerationFacet) rest.Facets[n];
					string enumName = codeIdents.AddUnique(CodeIdentifier.MakeValid (enu.Value), enu);
					members [n] = new EnumMap.EnumMapMember (enu.Value, enumName);
					members [n].Documentation = GetDocumentation (enu);
				}
				enumMap.ObjectMap = new EnumMap (members, isFlags);
				enumMap.IsSimpleType = true;
				return enumMap;
			}

			if (stype.Content is XmlSchemaSimpleTypeList)
			{
				XmlSchemaSimpleTypeList slist = (XmlSchemaSimpleTypeList)stype.Content;
				TypeData arrayTypeData = FindBuiltInType (slist.ItemTypeName, stype);

				ListMap listMap = new ListMap ();

				listMap.ItemInfo = new XmlTypeMapElementInfoList ();
				listMap.ItemInfo.Add (CreateElementInfo (typeQName.Namespace, null, "Item", arrayTypeData.ListItemTypeData, false, XmlSchemaForm.None));

				XmlTypeMapping map = CreateArrayTypeMapping (typeQName, arrayTypeData);
				map.ObjectMap = listMap;
				map.IsSimpleType = true;
				return map;
			}

			// It is an extension of a primitive or known type
			
			TypeData typeData = FindBuiltInType (typeQName, stype);
			return GetTypeMapping (typeData);
		}

		bool CanBeEnum (XmlSchemaSimpleType stype)
		{
			if (stype.Content is XmlSchemaSimpleTypeRestriction)
			{
				XmlSchemaSimpleTypeRestriction rest = (XmlSchemaSimpleTypeRestriction)stype.Content;
				if (rest.Facets.Count == 0) return false;
				foreach (object ob in rest.Facets)
					if (!(ob is XmlSchemaEnumerationFacet)) return false;
				return true;
			}
			else if (stype.Content is XmlSchemaSimpleTypeList)
			{
				XmlSchemaSimpleTypeList list = (XmlSchemaSimpleTypeList) stype.Content;
				return (list.ItemType != null && CanBeEnum (list.ItemType));
			}
			return false;
		}

		bool CanBeArray (XmlQualifiedName typeQName, XmlSchemaComplexType stype)
		{
			if (encodedFormat)
			{
				XmlSchemaComplexContent content = stype.ContentModel as XmlSchemaComplexContent;
				if (content == null) return false;
				XmlSchemaComplexContentRestriction rest = content.Content as XmlSchemaComplexContentRestriction;
				if (rest == null) return false;
				return rest.BaseTypeName == arrayType;
			}
			else
			{
				if (stype.Attributes.Count > 0 || stype.AnyAttribute != null) return false;
				else return !stype.IsMixed && CanBeArray (typeQName, stype.Particle, false);
			}
		}

		bool CanBeArray (XmlQualifiedName typeQName, XmlSchemaParticle particle, bool multiValue)
		{
			// To be an array, there can't be a direct child of type typeQName

			if (particle == null) return false;

			multiValue = multiValue || particle.MaxOccurs > 1;

			if (particle is XmlSchemaGroupRef)
				return CanBeArray (typeQName, GetRefGroupParticle ((XmlSchemaGroupRef)particle), multiValue);

			if (particle is XmlSchemaElement)
			{
				XmlSchemaElement elem = (XmlSchemaElement)particle;
				if (!elem.RefName.IsEmpty)
					return CanBeArray (typeQName, FindRefElement (elem), multiValue);
				else
					return multiValue && !typeQName.Equals (((XmlSchemaElement)particle).SchemaTypeName);
			}

			if (particle is XmlSchemaAny)
				return multiValue;

			if (particle is XmlSchemaSequence)
			{
				XmlSchemaSequence seq = particle as XmlSchemaSequence;
				if (seq.Items.Count != 1) return false;
				return CanBeArray (typeQName, (XmlSchemaParticle)seq.Items[0], multiValue);
			}

			if (particle is XmlSchemaChoice)
			{
				// Can be array if all choices have different types
				ArrayList types = new ArrayList ();
				if(!CheckChoiceType (typeQName, particle, types, ref multiValue)) return false;
				return multiValue;
			}

			return false;
		}

		bool CheckChoiceType (XmlQualifiedName typeQName, XmlSchemaParticle particle, ArrayList types, ref bool multiValue)
		{
			XmlQualifiedName type = null;

			multiValue = multiValue || particle.MaxOccurs > 1;

			if (particle is XmlSchemaGroupRef)
				return CheckChoiceType (typeQName, GetRefGroupParticle ((XmlSchemaGroupRef)particle), types, ref multiValue);

			if (particle is XmlSchemaElement) {
				string ns;
				XmlSchemaElement elem = (XmlSchemaElement)particle;
				XmlSchemaElement refElem = GetRefElement (typeQName, elem, out ns);
				if (refElem.SchemaType != null) return true;
				type = refElem.SchemaTypeName;
			}
			else if (particle is XmlSchemaAny) {
				type = anyType;
			}
			else if (particle is XmlSchemaSequence)
			{
				XmlSchemaSequence seq = particle as XmlSchemaSequence;
				foreach (XmlSchemaParticle par in seq.Items)
					if (!CheckChoiceType (typeQName, par, types, ref multiValue)) return false;
				return true;
			}
			else if (particle is XmlSchemaChoice)
			{
				foreach (XmlSchemaParticle choice in ((XmlSchemaChoice)particle).Items)
					if (!CheckChoiceType (typeQName, choice, types, ref multiValue)) return false;
				return true;
			}

			if (typeQName.Equals (type)) return false;

			// For primitive types, compare using CLR types, since several
			// xml types can be mapped to a single CLR type

			string t;
			if (IsPrimitiveTypeNamespace (type.Namespace))
				t = TypeTranslator.GetPrimitiveTypeData (type.Name).FullTypeName + ":" + type.Namespace;

			else
				t = type.Name + ":" + type.Namespace;

			if (types.Contains (t)) return false;
			types.Add (t);
			return true;
		}
		
		bool CanBeAnyElement (XmlSchemaComplexType stype)
		{
			XmlSchemaSequence seq = stype.Particle as XmlSchemaSequence;
			return (seq != null) && (seq.Items.Count == 1) && (seq.Items[0] is XmlSchemaAny);
		}
		
		Type GetAnyElementType (XmlSchemaComplexType stype)
		{
			XmlSchemaSequence seq = stype.Particle as XmlSchemaSequence;
			
			if ((seq == null) || (seq.Items.Count != 1) || !(seq.Items[0] is XmlSchemaAny))
				return null;
			
			if (encodedFormat) 
				return typeof(object);

			XmlSchemaAny any = seq.Items[0] as XmlSchemaAny;
			if (any.MaxOccurs == 1)
			{
				if (stype.IsMixed)
					return typeof(XmlNode);
				else
					return typeof(XmlElement);
			}
			else
			{
				if (stype.IsMixed)
					return typeof(XmlNode[]);
				else
					return typeof(XmlElement[]);
			}
		}

		bool CanBeIXmlSerializable (XmlSchemaComplexType stype)
		{
			XmlSchemaSequence seq = stype.Particle as XmlSchemaSequence;
			if (seq == null) return false;
			if (seq.Items.Count != 2) return false;
			XmlSchemaElement elem = seq.Items[0] as XmlSchemaElement;
			if (elem == null) return false;
			if (elem.RefName != new XmlQualifiedName ("schema",XmlSchema.Namespace)) return false;
			return (seq.Items[1] is XmlSchemaAny);
		}
		
		XmlTypeMapping ImportXmlSerializableMapping (string ns)
		{
			XmlQualifiedName qname = new XmlQualifiedName ("System.Data.DataSet",ns);
			XmlTypeMapping map = mappedTypes [qname] as XmlTypeMapping;
			if (map != null) return map;
			
			TypeData typeData = new TypeData ("System.Data.DataSet", "System.Data.DataSet", "System.Data.DataSet", SchemaTypes.XmlSerializable, null);
			map = new XmlTypeMapping ("System.Data.DataSet", "", typeData, "System.Data.DataSet", ns);
			map.IncludeInSchema = true;
			mappedTypes [qname] = map;
			dataMappedTypes [typeData] = map;
			return map;
		}
		
		XmlTypeMapElementInfo CreateElementInfo (string ns, XmlTypeMapMember member, string name, TypeData typeData, bool isNillable, XmlSchemaForm form)
		{
			if (typeData.IsComplexType)
				return CreateElementInfo (ns, member, name, typeData, isNillable, form, GetTypeMapping (typeData));
			else
				return CreateElementInfo (ns, member, name, typeData, isNillable, form, null);
		}
		
		XmlTypeMapElementInfo CreateElementInfo (string ns, XmlTypeMapMember member, string name, TypeData typeData, bool isNillable, XmlSchemaForm form, XmlTypeMapping emap)
		{
			XmlTypeMapElementInfo einfo = new XmlTypeMapElementInfo (member, typeData);
			einfo.ElementName = name;
			einfo.Namespace = ns;
			einfo.IsNullable = isNillable;
			einfo.Form = form;
			if (typeData.IsComplexType)
				einfo.MappedType = emap;
			return einfo;
		}

		XmlTypeMapElementInfo CreateTextElementInfo (string ns, XmlTypeMapMember member, TypeData typeData)
		{
			XmlTypeMapElementInfo einfo = new XmlTypeMapElementInfo (member, typeData);
			einfo.IsTextElement = true;
			einfo.WrappedElement = false;
			if (typeData.IsComplexType)
				einfo.MappedType = GetTypeMapping (typeData);
			return einfo;
		}

		XmlTypeMapping CreateTypeMapping (XmlQualifiedName typeQName, SchemaTypes schemaType, XmlQualifiedName root)
		{
			string typeName = CodeIdentifier.MakeValid (typeQName.Name);
			typeName = typeIdentifiers.AddUnique (typeName, null);

			TypeData typeData = new TypeData (typeName, typeName, typeName, schemaType, null);

			string rootElem;
			string rootNs;
			if (root != null) {
				rootElem = root.Name;
				rootNs = root.Namespace;
			}
			else {
				rootElem = typeQName.Name;
				rootNs = "";
			}
			
			XmlTypeMapping map = new XmlTypeMapping (rootElem, rootNs, typeData, typeQName.Name, typeQName.Namespace);
			map.IncludeInSchema = true;
			mappedTypes [typeQName] = map;
			dataMappedTypes [typeData] = map;

			return map;
		}

		XmlTypeMapping CreateArrayTypeMapping (XmlQualifiedName typeQName, TypeData arrayTypeData)
		{
			XmlTypeMapping map;
			if (encodedFormat) map = new XmlTypeMapping ("Array", XmlSerializer.EncodingNamespace, arrayTypeData, "Array", XmlSerializer.EncodingNamespace);
			else map = new XmlTypeMapping (arrayTypeData.XmlType, typeQName.Namespace, arrayTypeData, arrayTypeData.XmlType, typeQName.Namespace);
			
			map.IncludeInSchema = true;
			mappedTypes [typeQName] = map;
			dataMappedTypes [arrayTypeData] = map;

			return map;
		}

		XmlSchemaElement GetRefElement (XmlQualifiedName typeQName, XmlSchemaElement elem, out string ns)
		{

			if (!elem.RefName.IsEmpty)
			{
				ns = elem.RefName.Namespace;
				return FindRefElement (elem);
			}
			else
			{
				ns = typeQName.Namespace;
				return elem;
			}
		}

		XmlSchemaAttribute GetRefAttribute (XmlQualifiedName typeQName, XmlSchemaAttribute attr, out string ns)
		{
			if (!attr.RefName.IsEmpty)
			{
				ns = attr.RefName.Namespace;
				XmlSchemaAttribute at = FindRefAttribute (attr.RefName);
				if (at == null) throw new InvalidOperationException ("The attribute " + attr.RefName + " is missing");
				return at;
			}
			else
			{
				ns = typeQName.Namespace;
				return attr;
			}
		}

		TypeData GetElementTypeData (XmlQualifiedName typeQName, XmlSchemaElement elem, XmlQualifiedName root, out XmlTypeMapping map)
		{
			bool sharedAnnType = false;
			map = null;
			
			if (!elem.RefName.IsEmpty) {
				XmlSchemaElement refElem = FindRefElement (elem);
				if (refElem == null) throw new InvalidOperationException ("Global element not found: " + elem.RefName);
				root = elem.RefName;
				elem = refElem;
				sharedAnnType = true;
			}

			TypeData td;
			if (!elem.SchemaTypeName.IsEmpty) {
				td = GetTypeData (elem.SchemaTypeName, root);
				map = GetRegisteredTypeMapping (elem.SchemaTypeName);
			}
			else if (elem.SchemaType == null) 
				td = TypeTranslator.GetTypeData (typeof(object));
			else 
				td = GetTypeData (elem.SchemaType, typeQName, elem.Name, sharedAnnType, root);
			
			if (map == null && td.IsComplexType)
				map = GetTypeMapping (td);
				
			return td;
		}

		TypeData GetAttributeTypeData (XmlQualifiedName typeQName, XmlSchemaAttribute attr)
		{
			bool sharedAnnType = false;

			if (!attr.RefName.IsEmpty) {
				XmlSchemaAttribute refAtt = FindRefAttribute (attr.RefName);
				if (refAtt == null) throw new InvalidOperationException ("Global attribute not found: " + attr.RefName);
				attr = refAtt;
				sharedAnnType = true;
			}
			
			if (!attr.SchemaTypeName.IsEmpty) return GetTypeData (attr.SchemaTypeName, null);
			if (attr.SchemaType == null) return TypeTranslator.GetTypeData (typeof(string));
			else return GetTypeData (attr.SchemaType, typeQName, attr.Name, sharedAnnType, null);
		}

		TypeData GetTypeData (XmlQualifiedName typeQName, XmlQualifiedName root)
		{
			if (IsPrimitiveTypeNamespace (typeQName.Namespace)) {
				XmlTypeMapping map = ImportType (typeQName, root, false);
				if (map != null) return map.TypeData;
				else return TypeTranslator.GetPrimitiveTypeData (typeQName.Name);
			}
			
			if (encodedFormat && typeQName.Namespace == "")
				return TypeTranslator.GetPrimitiveTypeData (typeQName.Name);

			return ImportType (typeQName, root, true).TypeData;
		}

		TypeData GetTypeData (XmlSchemaType stype, XmlQualifiedName typeQNname, string propertyName, bool sharedAnnType, XmlQualifiedName root)
		{
			string baseName;

			if (sharedAnnType)
			{
				// Anonymous types defined in root elements or attributes can be shared among all elements that
				// reference this root element or attribute
				TypeData std = sharedAnonymousTypes [stype] as TypeData;
				if (std != null) return std;
				baseName = propertyName;
			}
			else
				baseName = typeQNname.Name + typeIdentifiers.MakeRightCase (propertyName);

			baseName = elemIdentifiers.AddUnique (baseName, stype);
			
			XmlQualifiedName newName;
			newName = new XmlQualifiedName (baseName, typeQNname.Namespace);

			XmlTypeMapping map = ImportType (newName, stype, root);
			if (sharedAnnType) sharedAnonymousTypes [stype] = map.TypeData;

			return map.TypeData;
		}

		XmlTypeMapping GetTypeMapping (TypeData typeData)
		{
			if (typeData.Type == typeof(object) && !anyTypeImported)
				ImportAllObjectTypes ();
				
			XmlTypeMapping map = (XmlTypeMapping) dataMappedTypes [typeData];
			if (map != null) return map;
			
			if (typeData.IsListType)
			{
				// Create an array map for the type

				XmlTypeMapping itemMap = GetTypeMapping (typeData.ListItemTypeData);
				
				map = new XmlTypeMapping (typeData.XmlType, itemMap.Namespace, typeData, typeData.XmlType, itemMap.Namespace);
				map.IncludeInSchema = true;

				ListMap listMap = new ListMap ();
				listMap.ItemInfo = new XmlTypeMapElementInfoList();
				listMap.ItemInfo.Add (CreateElementInfo (itemMap.Namespace, null, typeData.ListItemTypeData.XmlType, typeData.ListItemTypeData, false, XmlSchemaForm.None));
				map.ObjectMap = listMap;
				
				mappedTypes [new XmlQualifiedName(map.ElementName, map.Namespace)] = map;
				dataMappedTypes [typeData] = map;
				return map;
			}
			else if (typeData.SchemaType == SchemaTypes.Primitive || typeData.Type == typeof(object) || typeof(XmlNode).IsAssignableFrom(typeData.Type))
			{
				return CreateSystemMap (typeData);
			}
			
			throw new InvalidOperationException ("Map for type " + typeData.TypeName + " not found");
		}
		
		void AddObjectDerivedMap (XmlTypeMapping map)
		{
			TypeData typeData = TypeTranslator.GetTypeData (typeof(object));
			XmlTypeMapping omap = (XmlTypeMapping) dataMappedTypes [typeData];
			if (omap == null)
				omap = CreateSystemMap (typeData);
			omap.DerivedTypes.Add (map);
		}
		
		XmlTypeMapping CreateSystemMap (TypeData typeData)
		{
			XmlTypeMapping map = new XmlTypeMapping (typeData.XmlType, XmlSchema.Namespace, typeData, typeData.XmlType, XmlSchema.Namespace);
			map.IncludeInSchema = false;
			map.ObjectMap = new ClassMap ();
			dataMappedTypes [typeData] = map;
			return map;
		}
		
		void ImportAllObjectTypes ()
		{
			// All complex types are subtypes of anyType, so all of them 
			// must also be imported
			
			anyTypeImported = true;
			foreach (XmlSchema schema in schemas) {
				foreach (XmlSchemaObject sob in schema.Items) 
				{
					XmlSchemaComplexType sct = sob as XmlSchemaComplexType;
					if (sct != null)
						ImportType (new XmlQualifiedName (sct.Name, schema.TargetNamespace), sct, null);
				}
			}					
		}
		

		XmlTypeMapping GetRegisteredTypeMapping (XmlQualifiedName typeQName)
		{
			return (XmlTypeMapping) mappedTypes [typeQName];
		}

		XmlSchemaParticle GetRefGroupParticle (XmlSchemaGroupRef refGroup)
		{
			XmlSchemaGroup grp = (XmlSchemaGroup) schemas.Find (refGroup.RefName, typeof (XmlSchemaGroup));
			return grp.Particle;
		}

		XmlSchemaElement FindRefElement (XmlSchemaElement elem)
		{
			XmlSchemaElement refelem = (XmlSchemaElement) schemas.Find (elem.RefName, typeof(XmlSchemaElement));
			if (refelem != null) return refelem;
			
			if (IsPrimitiveTypeNamespace (elem.RefName.Namespace))
			{
				if (anyElement != null) return anyElement;
				anyElement = new XmlSchemaElement ();
				anyElement.Name = "any";
				anyElement.SchemaTypeName = anyType;
				return anyElement;
			} else
				return null;
		}
		
		XmlSchemaAttribute FindRefAttribute (XmlQualifiedName refName)
		{
			if (refName.Namespace == XmlNamespace)
			{
				XmlSchemaAttribute at = new XmlSchemaAttribute ();
				at.Name = refName.Name;
				at.SchemaTypeName = new XmlQualifiedName ("string",XmlSchema.Namespace);
				return at;
			}
			return (XmlSchemaAttribute) schemas.Find (refName, typeof(XmlSchemaAttribute));
		}
		
		XmlSchemaAttributeGroup FindRefAttributeGroup (XmlQualifiedName refName)
		{
			XmlSchemaAttributeGroup grp = (XmlSchemaAttributeGroup) schemas.Find (refName, typeof(XmlSchemaAttributeGroup));
			foreach (XmlSchemaObject at in grp.Attributes)
			{
				if (at is XmlSchemaAttributeGroupRef && ((XmlSchemaAttributeGroupRef)at).RefName == refName)
					throw new InvalidOperationException ("Cannot import attribute group '" + refName.Name + "' from namespace '" + refName.Namespace + "'. Redefine not supported");
					
			}
			return grp;
		}
		
		XmlTypeMapping ReflectType (Type type, string ns)
		{
			if (!encodedFormat)
			{
				if (auxXmlRefImporter == null) auxXmlRefImporter = new XmlReflectionImporter ();
				return auxXmlRefImporter.ImportTypeMapping (type, ns);
			}
			else
			{
				if (auxSoapRefImporter == null) auxSoapRefImporter = new SoapReflectionImporter ();
				return auxSoapRefImporter.ImportTypeMapping (type, ns);
			}
		}


		string GetDocumentation (XmlSchemaAnnotated elem)
		{
			string res = "";
			XmlSchemaAnnotation anot = elem.Annotation;
			if (anot == null || anot.Items == null) return null;
			
			foreach (object ob in anot.Items)
			{
				XmlSchemaDocumentation doc = ob as XmlSchemaDocumentation;
				if (doc != null && doc.Markup != null && doc.Markup.Length > 0) {
					if (res != string.Empty) res += "\n";
					foreach (XmlNode node in doc.Markup)
						res += node.Value;
				}
			}
			return res;
		}
		
		bool IsPrimitiveTypeNamespace (string ns)
		{
			return (ns == XmlSchema.Namespace) || (encodedFormat && ns == XmlSerializer.EncodingNamespace);
		}

		#endregion // Methods
	}
}