merge -r 53370:58178
[mono.git] / mcs / class / System.XML / System.Xml.Schema / XmlSchemaValidator.cs
1 //
2 // XmlSchemaValidator.cs
3 //
4 // Author:
5 //      Atsushi Enomoto  <atsushi@ximian.com>
6 //
7 // (C)2004 Novell Inc,
8 //
9
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 //
32 // LAMESPEC:
33 //      - There is no assurance that xsi:type precedes to any other attributes,
34 //        or xsi:type is not handled.
35 //      - There is no SourceUri provision.
36 //
37
38 #if NET_2_0
39
40 using System;
41 using System.Collections;
42 using System.IO;
43 using System.Text;
44 using System.Xml;
45 using Mono.Xml.Schema;
46
47 using QName = System.Xml.XmlQualifiedName;
48 using Form = System.Xml.Schema.XmlSchemaForm;
49 using Use = System.Xml.Schema.XmlSchemaUse;
50 using ContentType = System.Xml.Schema.XmlSchemaContentType;
51 using Validity = System.Xml.Schema.XmlSchemaValidity;
52 using ValidationFlags = System.Xml.Schema.XmlSchemaValidationFlags;
53 using ContentProc = System.Xml.Schema.XmlSchemaContentProcessing;
54 using SOMList = System.Xml.Schema.XmlSchemaObjectCollection;
55 using SOMObject = System.Xml.Schema.XmlSchemaObject;
56 using XsElement = System.Xml.Schema.XmlSchemaElement;
57 using XsAttribute = System.Xml.Schema.XmlSchemaAttribute;
58 using AttrGroup = System.Xml.Schema.XmlSchemaAttributeGroup;
59 using AttrGroupRef = System.Xml.Schema.XmlSchemaAttributeGroupRef;
60 using XsDatatype = System.Xml.Schema.XmlSchemaDatatype;
61 using SimpleType = System.Xml.Schema.XmlSchemaSimpleType;
62 using ComplexType = System.Xml.Schema.XmlSchemaComplexType;
63 using SimpleModel = System.Xml.Schema.XmlSchemaSimpleContent;
64 using SimpleExt = System.Xml.Schema.XmlSchemaSimpleContentExtension;
65 using SimpleRst = System.Xml.Schema.XmlSchemaSimpleContentRestriction;
66 using ComplexModel = System.Xml.Schema.XmlSchemaComplexContent;
67 using ComplexExt = System.Xml.Schema.XmlSchemaComplexContentExtension;
68 using ComplexRst = System.Xml.Schema.XmlSchemaComplexContentRestriction;
69 using SimpleTypeRest = System.Xml.Schema.XmlSchemaSimpleTypeRestriction;
70 using SimpleTypeList = System.Xml.Schema.XmlSchemaSimpleTypeList;
71 using SimpleTypeUnion = System.Xml.Schema.XmlSchemaSimpleTypeUnion;
72 using SchemaFacet = System.Xml.Schema.XmlSchemaFacet;
73 using LengthFacet = System.Xml.Schema.XmlSchemaLengthFacet;
74 using MinLengthFacet = System.Xml.Schema.XmlSchemaMinLengthFacet;
75 using Particle = System.Xml.Schema.XmlSchemaParticle;
76 using Sequence = System.Xml.Schema.XmlSchemaSequence;
77 using Choice = System.Xml.Schema.XmlSchemaChoice;
78 using ValException = System.Xml.Schema.XmlSchemaValidationException;
79
80
81 namespace System.Xml.Schema
82 {
83         public sealed class XmlSchemaValidator
84         {
85                 enum Transition {
86                         None,
87                         Content,
88                         StartTag,
89                         Finished
90                 }
91
92                 static readonly XsAttribute [] emptyAttributeArray =
93                         new XsAttribute [0];
94
95                 public XmlSchemaValidator (
96                         XmlNameTable nameTable,
97                         XmlSchemaSet schemas,
98                         IXmlNamespaceResolver nsResolver,
99                         ValidationFlags options)
100                 {
101                         this.nameTable = nameTable;
102                         this.schemas = schemas;
103                         this.nsResolver = nsResolver;
104                         this.options = options;
105                 }
106
107                 #region Fields
108
109                 // XmlReader/XPathNavigator themselves
110                 object nominalEventSender;
111                 IXmlLineInfo lineInfo;
112                 IXmlNamespaceResolver nsResolver;
113                 Uri sourceUri;
114
115                 // These fields will be from XmlReaderSettings or 
116                 // XPathNavigator.CheckValidity(). BTW, I think we could
117                 // implement XPathNavigator.CheckValidity() with
118                 // XsdValidatingReader.
119                 XmlNameTable nameTable;
120                 XmlSchemaSet schemas;
121                 XmlResolver xmlResolver = new XmlUrlResolver ();
122
123                 // "partialValidationType". but not sure how it will be used.
124                 SOMObject startType;
125
126                 // It is perhaps from XmlReaderSettings, but XPathNavigator
127                 // does not have it.
128                 ValidationFlags options;
129
130                 // Validation state
131                 Transition transition;
132                 XsdParticleStateManager state;
133
134                 ArrayList occuredAtts = new ArrayList ();
135                 XsAttribute [] defaultAttributes = emptyAttributeArray;
136                 ArrayList defaultAttributesCache = new ArrayList ();
137
138 #region ID Constraints
139                 XsdIDManager idManager = new XsdIDManager ();
140 #endregion
141
142 #region Key Constraints
143                 ArrayList keyTables = new ArrayList ();
144                 ArrayList currentKeyFieldConsumers = new ArrayList ();
145                 ArrayList tmpKeyrefPool;
146 #endregion
147                 ArrayList elementQNameStack = new ArrayList ();
148
149                 StringBuilder storedCharacters = new StringBuilder ();
150                 bool shouldValidateCharacters;
151
152                 int depth;
153                 int xsiNilDepth = -1;
154                 int skipValidationDepth = -1;
155
156                 SOMObject currentType;
157
158
159                 #endregion
160
161                 #region Public properties
162
163                 // Settable Properties
164
165                 // IMHO It should just be an event that fires another event.
166                 public event ValidationEventHandler ValidationEventHandler;
167
168                 public object ValidationEventSender {
169                         get { return nominalEventSender; }
170                         set { nominalEventSender = value; }
171                 }
172
173                 // (kinda) Construction Properties
174
175                 public IXmlLineInfo LineInfoProvider {
176                         get { return lineInfo; }
177                         set { lineInfo = value; }
178                 }
179
180                 public XmlResolver XmlResolver {
181                         set { xmlResolver = value; }
182                 }
183
184                 [MonoTODO]
185                 public Uri SourceUri {
186                         get { return sourceUri; }
187                         // FIXME: actually there seems no setter, but then
188                         // it will never make sense.
189                         set { sourceUri = value; }
190                 }
191                 #endregion
192
193                 #region Private properties
194
195                 private string BaseUri {
196                         get { return sourceUri != null ? sourceUri.AbsoluteUri : String.Empty; }
197                 }
198
199                 private XsdValidationContext Context {
200                         get { return state.Context; }
201                 }
202
203                 private bool IgnoreWarnings {
204                         get { return (options & ValidationFlags
205                                 .ReportValidationWarnings) == 0; }
206                 }
207
208                 private bool IgnoreIdentity {
209                         get { return (options & ValidationFlags
210                                 .ProcessIdentityConstraints) == 0; }
211                 }
212
213                 #endregion
214
215                 #region Public methods
216
217                 // State Monitor
218
219                 public XmlSchemaAttribute [] GetExpectedAttributes ()
220                 {
221                         ComplexType cType = Context.ActualType as ComplexType;
222                         if (cType == null)
223                                 return emptyAttributeArray;
224                         ArrayList al = new ArrayList ();
225                         foreach (DictionaryEntry entry in cType.AttributeUses)
226                                 if (!occuredAtts.Contains ((QName) entry.Key))
227                                         al.Add (entry.Value);
228                         return (XsAttribute [])
229                                 al.ToArray (typeof (XsAttribute));
230                 }
231
232                 private void CollectAtomicParticles (XmlSchemaParticle p,
233                         ArrayList al)
234                 {
235                         if (p is XmlSchemaGroupBase) {
236                                 foreach (XmlSchemaParticle c in 
237                                         ((XmlSchemaGroupBase) p).Items)
238                                         CollectAtomicParticles (c, al);
239                         }
240                         else
241                                 al.Add (p);
242                 }
243
244                 [MonoTODO ("Need some tests.")]
245                 // Its behavior is not obvious. For example, it does not
246                 // contain groups (xs:sequence/xs:choice/xs:all). Since it
247                 // might contain xs:any, it could not be of type element[].
248                 public XmlSchemaParticle [] GetExpectedParticles ()
249                 {
250                         ArrayList al = new ArrayList ();
251                         Context.State.GetExpectedParticles (al);
252                         ArrayList ret = new ArrayList ();
253
254                         foreach (XmlSchemaParticle p in al)
255                                 CollectAtomicParticles (p, ret);
256
257                         return (XmlSchemaParticle []) ret.ToArray (
258                                 typeof (XmlSchemaParticle));
259                 }
260
261                 public void GetUnspecifiedDefaultAttributes (ArrayList list)
262                 {
263                         if (transition != Transition.StartTag)
264                                 throw new InvalidOperationException ("Method 'GetUnsoecifiedDefaultAttributes' works only when the validator state is inside a start tag.");
265                         foreach (XmlSchemaAttribute attr
266                                 in GetExpectedAttributes ())
267                                 if (attr.ValidatedDefaultValue != null || attr.ValidatedFixedValue != null)
268                                         list.Add (attr);
269
270                         list.AddRange (defaultAttributes);
271                 }
272
273                 // State Controller
274
275                 public void AddSchema (XmlSchema schema)
276                 {
277                         schemas.Add (schema);
278                         schemas.Compile ();
279                 }
280
281                 public void Initialize ()
282                 {
283                         Initialize (null);
284                 }
285
286                 public void Initialize (SOMObject startType)
287                 {
288                         this.startType = startType;
289                         transition = Transition.Content;
290                         state = new XsdParticleStateManager ();
291                         if (!schemas.IsCompiled)
292                                 schemas.Compile ();
293                 }
294
295                 // It must be called at the end of the validation (to check
296                 // identity constraints etc.).
297                 public void EndValidation ()
298                 {
299                         CheckState (Transition.Content);
300                         transition = Transition.Finished;
301
302                         if (schemas.Count == 0)
303                                 return;
304
305                         if (depth > 0)
306                                 throw new InvalidOperationException (String.Format ("There are {0} open element(s). ValidateEndElement() must be called for each open element.", depth));
307
308                         // 3.3.4 ElementLocallyValidElement 7 = Root Valid.
309                         if (!IgnoreIdentity &&
310                                 idManager.HasMissingIDReferences ())
311                                 HandleError ("There are missing ID references: " + idManager.GetMissingIDString ());
312                 }
313
314                 // I guess it is for validation error recovery
315                 [MonoTODO ("Find out how XmlSchemaInfo is used.")]
316                 public void SkipToEndElement (XmlSchemaInfo info)
317                 {
318                         CheckState (Transition.Content);
319                         if (schemas.Count == 0)
320                                 return;
321                         state.PopContext ();
322                 }
323
324                 public object ValidateAttribute (
325                         string localName,
326                         string ns,
327                         string attributeValue,
328                         XmlSchemaInfo info)
329                 {
330                         return ValidateAttribute (localName, ns,
331                                 delegate () { return info.SchemaType.Datatype.ParseValue (attributeValue, nameTable, nsResolver); },
332                                 info);
333                 }
334
335                 // I guess this weird XmlValueGetter is for such case that
336                 // value might not be required (and thus it improves 
337                 // performance in some cases. Doh).
338
339                 // The return value is typed primitive, is possible.
340                 // AttDeriv
341                 public object ValidateAttribute (
342                         string localName,
343                         string ns,
344                         XmlValueGetter attributeValue,
345                         XmlSchemaInfo info)
346                 {
347                         CheckState (Transition.StartTag);
348
349                         QName qname = new QName (localName, ns);
350                         if (occuredAtts.Contains (qname))
351                                 throw new InvalidOperationException (String.Format ("Attribute '{0}' has already been validated in the same element.", qname));
352                         occuredAtts.Add (qname);
353
354                         if (ns == XmlNamespaceManager.XmlnsXmlns)
355                                 return null;
356
357                         if (schemas.Count == 0)
358                                 return null;
359
360                         // 3.3.4 Element Locally Valid (Type) - attribute
361                         if (Context.ActualType is ComplexType)
362                                 return AssessAttributeElementLocallyValidType (localName, ns, attributeValue, info);
363                         else
364                                 HandleError ("Current simple type cannot accept attributes other than schema instance namespace.");
365                         return null;
366                 }
367
368                 // StartTagOpenDeriv
369                 public void ValidateElement (
370                         string localName,
371                         string ns,
372                         XmlSchemaInfo info)
373                 {
374                         ValidateElement (localName, ns, info, null, null, null, null);
375                 }
376
377                 public void ValidateElement (
378                         string localName,
379                         string ns,
380                         XmlSchemaInfo info,
381                         string xsiType,
382                         string xsiNil,
383                         string schemaLocation,
384                         string noNsSchemaLocation)
385                 {
386                         CheckState (Transition.Content);
387                         transition = Transition.StartTag;
388
389                         if (schemaLocation != null)
390                                 HandleSchemaLocation (schemaLocation);
391                         if (noNsSchemaLocation != null)
392                                 HandleNoNSSchemaLocation (noNsSchemaLocation);
393
394                         elementQNameStack.Add (new XmlQualifiedName (localName, ns));
395
396                         if (schemas.Count == 0)
397                                 return;
398
399 #region ID Constraints
400                         if (!IgnoreIdentity)
401                                 idManager.OnStartElement ();
402 #endregion
403                         defaultAttributes = emptyAttributeArray;
404
405                         // If there is no schema information, then no validation is performed.
406                         if (skipValidationDepth < 0 || depth <= skipValidationDepth) {
407                                 if (shouldValidateCharacters)
408                                         ValidateEndSimpleContent (null);
409
410                                 AssessOpenStartElementSchemaValidity (localName, ns);
411                         }
412
413                         if (xsiNil != null)
414                                 HandleXsiNil (xsiNil, info);
415                         if (xsiType != null)
416                                 HandleXsiType (xsiType);
417
418                         shouldValidateCharacters = true;
419
420                         if (info != null) {
421                                 info.IsNil = xsiNilDepth >= 0;
422                                 info.SchemaElement = Context.Element;
423                                 info.SchemaType = Context.ActualSchemaType;
424                                 info.SchemaAttribute = null;
425                                 info.IsDefault = false;
426                                 info.MemberType = null;
427                                 // FIXME: supply Validity (really useful?)
428                         }
429                 }
430
431                 public object ValidateEndElement (XmlSchemaInfo info)
432                 {
433                         return ValidateEndElement (info, null);
434                 }
435
436                 // The return value is typed primitive, if supplied.
437                 // Parameter 'var' seems to be converted into the type
438                 // represented by current simple content type. (try passing
439                 // some kind of object to this method to check the behavior.)
440                 // EndTagDeriv
441                 [MonoTODO ("Handle 'var' parameter.")]
442                 public object ValidateEndElement (XmlSchemaInfo info,
443                         object var)
444                 {
445                         // If it is going to validate an empty element, then
446                         // first validate end of attributes.
447                         if (transition == Transition.StartTag)
448                                 ValidateEndOfAttributes (info);
449
450                         CheckState (Transition.Content);
451
452                         elementQNameStack.RemoveAt (elementQNameStack.Count - 1);
453
454                         if (schemas.Count == 0)
455                                 return null;
456                         if (depth == 0)
457                                 throw new InvalidOperationException ("There was no corresponding call to 'ValidateElement' method.");
458
459                         depth--;
460
461                         object ret = null;
462                         if (depth == skipValidationDepth)
463                                 skipValidationDepth = -1;
464                         else if (skipValidationDepth < 0 || depth <= skipValidationDepth)
465                                 ret = AssessEndElementSchemaValidity (info);
466                         return ret;
467                 }
468
469                 // StartTagCloseDeriv
470                 // FIXME: fill validity inside this invocation.
471                 public void ValidateEndOfAttributes (XmlSchemaInfo info)
472                 {
473                         try {
474                                 CheckState (Transition.StartTag);
475                                 transition = Transition.Content;
476                                 if (schemas.Count == 0)
477                                         return;
478
479                                 AssessCloseStartElementSchemaValidity (info);
480                         } finally {
481                                 occuredAtts.Clear ();
482                         }
483                 }
484
485                 // LAMESPEC: It should also receive XmlSchemaInfo so that
486                 // a validator application can receive simple type or
487                 // or content type validation errors.
488                 public void ValidateText (string value)
489                 {
490                         ValidateText (delegate () { return value; });
491                 }
492
493                 // TextDeriv ... without text. Maybe typed check is done by
494                 // ValidateAtomicValue().
495                 public void ValidateText (XmlValueGetter getter)
496                 {
497                         CheckState (Transition.Content);
498                         if (schemas.Count == 0)
499                                 return;
500
501                         ComplexType ct = Context.ActualType as ComplexType;
502                         if (ct != null && storedCharacters.Length > 0) {
503                                 switch (ct.ContentType) {
504                                 case XmlSchemaContentType.ElementOnly:
505                                 case XmlSchemaContentType.Empty:
506                                         HandleError ("Not allowed character content was found.");
507                                         break;
508                                 }
509                         }
510
511                         ValidateCharacters (getter);
512                 }
513
514                 public void ValidateWhitespace (string value)
515                 {
516                         ValidateWhitespace (delegate () { return value; });
517                 }
518
519                 // TextDeriv...?
520                 [MonoTODO]
521                 public void ValidateWhitespace (XmlValueGetter getter)
522                 {
523                         CheckState (Transition.Content);
524                         if (schemas.Count == 0)
525                                 return;
526
527 //                      throw new NotImplementedException ();
528                 }
529
530                 #endregion
531
532                 #region Error handling
533
534                 private void HandleError (string message)
535                 {
536                         HandleError (message, null, false);
537                 }
538
539                 private void HandleError (
540                         string message, Exception innerException)
541                 {
542                         HandleError (message, innerException, false);
543                 }
544
545                 private void HandleError (string message,
546                         Exception innerException, bool isWarning)
547                 {
548                         if (isWarning && IgnoreWarnings)
549                                 return;
550
551                         ValException vex = new ValException (
552                                 message, nominalEventSender, BaseUri,
553                                 null, innerException);
554                         HandleError (vex, isWarning);
555                 }
556
557                 private void HandleError (ValException exception)
558                 {
559                         HandleError (exception, false);
560                 }
561
562                 private void HandleError (ValException exception, bool isWarning)
563                 {
564                         if (isWarning && IgnoreWarnings)
565                                 return;
566
567                         if (ValidationEventHandler == null)
568                                 throw exception;
569
570                         ValidationEventArgs e = new ValidationEventArgs (
571                                 exception,
572                                 exception.Message,
573                                 isWarning ? XmlSeverityType.Warning :
574                                         XmlSeverityType.Error);
575                         ValidationEventHandler (nominalEventSender, e);
576                 }
577
578                 #endregion
579
580                 private void CheckState (Transition expected)
581                 {
582                         if (transition != expected) {
583                                 if (transition == Transition.None)
584                                         throw new InvalidOperationException ("Initialize() must be called before processing validation.");
585                                 else
586                                         throw new InvalidOperationException (
587                                                 String.Format ("Unexpected attempt to validation state transition from {0} to {1} was happened.",
588                                                         transition,
589                                                         expected));
590                         }
591                 }
592
593                 private XsElement FindElement (string name, string ns)
594                 {
595                         return (XsElement) schemas.GlobalElements [new XmlQualifiedName (name, ns)];
596                 }
597
598                 private XmlSchemaType FindType (XmlQualifiedName qname)
599                 {
600                         return (XmlSchemaType) schemas.GlobalTypes [qname];
601                 }
602
603                 #region Type Validation
604
605                 private void ValidateStartElementParticle (
606                         string localName, string ns)
607                 {
608                         if (Context.State == null)
609                                 return;
610                         Context.XsiType = null;
611                         state.CurrentElement = null;
612                         Context.EvaluateStartElement (localName,
613                                 ns);
614                         if (Context.IsInvalid)
615                                 HandleError ("Invalid start element: " + ns + ":" + localName);
616
617                         Context.SetElement (state.CurrentElement);
618                 }
619
620                 private void AssessOpenStartElementSchemaValidity (
621                         string localName, string ns)
622                 {
623                         // If the reader is inside xsi:nil (and failed
624                         // on validation), then simply skip its content.
625                         if (xsiNilDepth >= 0 && xsiNilDepth < depth)
626                                 HandleError ("Element item appeared, while current element context is nil.");
627
628                         ValidateStartElementParticle (localName, ns);
629
630                         // Create Validation Root, if not exist.
631                         // [Schema Validity Assessment (Element) 1.1]
632                         if (Context.Element == null) {
633                                 state.CurrentElement = FindElement (localName, ns);
634                                 Context.SetElement (state.CurrentElement);
635                         }
636
637 #region Key Constraints
638                         if (!IgnoreIdentity)
639                                 ValidateKeySelectors ();
640                                 ValidateKeyFields (false, xsiNilDepth == depth,
641                                         Context.ActualType, null, null, null);
642 #endregion
643                 }
644
645                 private void AssessCloseStartElementSchemaValidity (XmlSchemaInfo info)
646                 {
647                         if (Context.XsiType != null)
648                                 AssessCloseStartElementLocallyValidType (info);
649                         else if (Context.Element != null) {
650                                 // element locally valid is checked only when
651                                 // xsi:type does not exist.
652                                 AssessElementLocallyValidElement ();
653                                 if (Context.Element.ElementType != null)
654                                         AssessCloseStartElementLocallyValidType (info);
655                         }
656
657                         if (Context.Element == null) {
658                                 switch (state.ProcessContents) {
659                                 case ContentProc.Skip:
660                                         break;
661                                 case ContentProc.Lax:
662                                         break;
663                                 default:
664                                         QName current = (QName) elementQNameStack [elementQNameStack.Count - 1];
665                                         if (Context.XsiType == null &&
666                                                 (schemas.Contains (current.Namespace) ||
667                                                 !schemas.MissedSubComponents (current.Namespace)))
668                                                 HandleError ("Element declaration for " + current + " is missing.");
669                                         break;
670                                 }
671                         }
672
673                         // Proceed to the next depth.
674
675                         state.PushContext ();
676
677                         XsdValidationState next = null;
678                         if (state.ProcessContents == ContentProc.Skip)
679                                 skipValidationDepth = depth;
680                         else {
681                                 // create child particle state.
682                                 ComplexType xsComplexType = Context.ActualType as ComplexType;
683                                 if (xsComplexType != null)
684                                         next = state.Create (xsComplexType.ValidatableParticle);
685                                 else if (state.ProcessContents == ContentProc.Lax)
686                                         next = state.Create (XmlSchemaAny.AnyTypeContent);
687                                 else
688                                         next = state.Create (XmlSchemaParticle.Empty);
689                         }
690                         Context.State = next;
691
692                         depth++;
693                 }
694
695                 // It must be invoked after xsi:nil turned out not to be in
696                 // this element.
697                 private void AssessElementLocallyValidElement ()
698                 {
699                         XsElement element = Context.Element;
700                         XmlQualifiedName qname = (XmlQualifiedName) elementQNameStack [elementQNameStack.Count - 1];
701                         // 1.
702                         if (element == null)
703                                 HandleError ("Element declaration is required for " + qname);
704                         // 2.
705                         if (element.ActualIsAbstract)
706                                 HandleError ("Abstract element declaration was specified for " + qname);
707                         // 3. is checked inside ValidateAttribute().
708                 }
709
710                 // 3.3.4 Element Locally Valid (Type)
711                 private void AssessCloseStartElementLocallyValidType (XmlSchemaInfo info)
712                 {
713                         object schemaType = Context.ActualType;
714                         if (schemaType == null) {       // 1.
715                                 HandleError ("Schema type does not exist.");
716                                 return;
717                         }
718                         ComplexType cType = schemaType as ComplexType;
719                         SimpleType sType = schemaType as SimpleType;
720                         if (sType != null) {
721                                 // 3.1.1.
722                                 // Attributes are checked in ValidateAttribute().
723                         } else if (cType != null) {
724                                 // 3.2. Also, 2. is checked there.
725                                 AssessCloseStartElementLocallyValidComplexType (cType, info);
726                         }
727                 }
728
729                 // 3.4.4 Element Locally Valid (Complex Type)
730                 // FIXME: use SchemaInfo for somewhere (? it is passed to ValidateEndOfAttributes() for some reason)
731                 private void AssessCloseStartElementLocallyValidComplexType (ComplexType cType, XmlSchemaInfo info)
732                 {
733                         // 1.
734                         if (cType.IsAbstract) {
735                                 HandleError ("Target complex type is abstract.");
736                                 return;
737                         }
738
739                         // 2 (xsi:nil and content prohibition)
740                         // See AssessStartElementSchemaValidity() and ValidateCharacters()
741                         // 3. attribute uses and  5. wild IDs are handled at
742                         // ValidateAttribute().
743
744                         // Collect default attributes.
745                         // 4.
746                         foreach (XsAttribute attr in GetExpectedAttributes ()) {
747                                 if (attr.ValidatedUse == XmlSchemaUse.Required && 
748                                         attr.ValidatedFixedValue == null)
749                                         HandleError ("Required attribute " + attr.QualifiedName + " was not found.");
750                                 else if (attr.ValidatedDefaultValue != null || attr.ValidatedFixedValue != null)
751                                         defaultAttributesCache.Add (attr);
752                         }
753                         if (defaultAttributesCache.Count == 0)
754                                 defaultAttributes = emptyAttributeArray;
755                         else
756                                 defaultAttributes = (XsAttribute []) 
757                                         defaultAttributesCache.ToArray (
758                                                 typeof (XsAttribute));
759                         defaultAttributesCache.Clear ();
760                         // 5. wild IDs was already checked at ValidateAttribute().
761
762                 }
763
764                 private object AssessAttributeElementLocallyValidType (string localName, string ns, XmlValueGetter getter, XmlSchemaInfo info)
765                 {
766                         ComplexType cType = Context.ActualType as ComplexType;
767                         XmlQualifiedName qname = new XmlQualifiedName (localName, ns);
768                         // including 3.10.4 Item Valid (Wildcard)
769                         XmlSchemaObject attMatch = XmlSchemaUtil.FindAttributeDeclaration (ns, schemas, cType, qname);
770                         if (attMatch == null)
771                                 HandleError ("Attribute declaration was not found for " + qname);
772                         XsAttribute attdecl = attMatch as XsAttribute;
773                         if (attdecl != null) {
774                                 AssessAttributeLocallyValidUse (attdecl);
775                                 return AssessAttributeLocallyValid (attdecl, info, getter);
776                         } // otherwise anyAttribute or null.
777                         return null;
778                 }
779
780                 // 3.2.4 Attribute Locally Valid and 3.4.4
781                 private object AssessAttributeLocallyValid (XsAttribute attr, XmlSchemaInfo info, XmlValueGetter getter)
782                 {
783                         // 2. - 4.
784                         if (attr.AttributeType == null)
785                                 HandleError ("Attribute type is missing for " + attr.QualifiedName);
786                         XsDatatype dt = attr.AttributeType as XsDatatype;
787                         if (dt == null)
788                                 dt = ((SimpleType) attr.AttributeType).Datatype;
789                         // It is a bit heavy process, so let's omit as long as possible ;-)
790                         if (dt != SimpleType.AnySimpleType || attr.ValidatedFixedValue != null) {
791                                 object parsedValue = null;
792                                 try {
793                                         parsedValue = getter ();
794                                 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
795                                         HandleError ("Attribute value is invalid against its data type " + dt.TokenizedType, ex);
796                                 }
797                                 XmlSchemaType type = info != null ? info.SchemaType : null;
798                                 if (attr.ValidatedFixedValue != null && 
799                                         !XmlSchemaUtil.IsSchemaDatatypeEquals (
800                                         attr.AttributeSchemaType.Datatype as XsdAnySimpleType, attr.ValidatedFixedTypedValue, type != null ? type.Datatype as XsdAnySimpleType : null, parsedValue)) {
801                                         HandleError ("The value of the attribute " + attr.QualifiedName + " does not match with its fixed value.");
802                                         parsedValue = attr.ValidatedFixedTypedValue;
803                                 }
804 #region ID Constraints
805                                 if (!IgnoreIdentity) {
806                                         string error = idManager.AssessEachAttributeIdentityConstraint (dt, parsedValue, ((QName) elementQNameStack [elementQNameStack.Count - 1]).Name);
807                                         if (error != null)
808                                                 HandleError (error);
809                                 }
810 #endregion
811
812                                 #region Key Constraints
813                                 if (!IgnoreIdentity)
814                                         ValidateKeyFields (
815                                                 true,
816                                                 false,
817                                                 attr.AttributeType,
818                                                 attr.QualifiedName.Name,
819                                                 attr.QualifiedName.Namespace,
820                                                 getter);
821                                 #endregion
822
823                                 return parsedValue;
824                         }
825                         return null;
826                 }
827
828                 private void AssessAttributeLocallyValidUse (XsAttribute attr)
829                 {
830                         // This is extra check than spec 3.5.4
831                         if (attr.ValidatedUse == XmlSchemaUse.Prohibited)
832                                 HandleError ("Attribute " + attr.QualifiedName + " is prohibited in this context.");
833                 }
834
835                 private object AssessEndElementSchemaValidity (
836                         XmlSchemaInfo info)
837                 {
838                         ValidateEndElementParticle ();  // validate against childrens' state.
839
840                         object ret = ValidateEndSimpleContent (info);
841
842                         // 3.3.4 Assess ElementLocallyValidElement 5: value constraints.
843                         // 3.3.4 Assess ElementLocallyValidType 3.1.3. = StringValid(3.14.4)
844                         // => ValidateEndSimpleContent ().
845
846 #region Key Constraints
847                         if (!IgnoreIdentity)
848                                 ValidateEndElementKeyConstraints ();
849 #endregion
850
851                         // Reset xsi:nil, if required.
852                         if (xsiNilDepth == depth)
853                                 xsiNilDepth = -1;
854                         return ret;
855                 }
856
857                 private void ValidateEndElementParticle ()
858                 {
859                         if (Context.State != null) {
860                                 if (!Context.EvaluateEndElement ()) {
861                                         HandleError ("Invalid end element. There are still required content items.");
862                                 }
863                         }
864                         state.PopContext ();
865                 }
866
867                 // Utility for missing validation completion related to child items.
868                 private void ValidateCharacters (XmlValueGetter getter)
869                 {
870                         if (xsiNilDepth >= 0 && xsiNilDepth < depth)
871                                 HandleError ("Element item appeared, while current element context is nil.");
872
873                         if (shouldValidateCharacters)
874                                 storedCharacters.Append (getter ());
875                 }
876
877
878                 // Utility for missing validation completion related to child items.
879                 private object ValidateEndSimpleContent (XmlSchemaInfo info)
880                 {
881                         object ret = null;
882                         if (shouldValidateCharacters)
883                                 ret = ValidateEndSimpleContentCore (info);
884                         shouldValidateCharacters = false;
885                         storedCharacters.Length = 0;
886                         return ret;
887                 }
888
889                 private object ValidateEndSimpleContentCore (XmlSchemaInfo info)
890                 {
891                         if (Context.ActualType == null)
892                                 return null;
893
894                         string value = storedCharacters.ToString ();
895                         object ret = null;
896
897                         if (value.Length == 0) {
898                                 // 3.3.4 Element Locally Valid (Element) 5.1.2
899                                 if (Context.Element != null) {
900                                         if (Context.Element.ValidatedDefaultValue != null)
901                                                 value = Context.Element.ValidatedDefaultValue;
902                                 }                                       
903                         }
904
905                         XsDatatype dt = Context.ActualType as XsDatatype;
906                         SimpleType st = Context.ActualType as SimpleType;
907                         if (dt == null) {
908                                 if (st != null) {
909                                         dt = st.Datatype;
910                                 } else {
911                                         ComplexType ct = Context.ActualType as ComplexType;
912                                         dt = ct.Datatype;
913                                         switch (ct.ContentType) {
914                                         case XmlSchemaContentType.ElementOnly:
915                                         case XmlSchemaContentType.Empty:
916                                                 if (value.Length > 0)
917                                                         HandleError ("Character content not allowed.");
918                                                 break;
919                                         }
920                                 }
921                         }
922                         if (dt != null) {
923                                 // 3.3.4 Element Locally Valid (Element) :: 5.2.2.2. Fixed value constraints
924                                 if (Context.Element != null && Context.Element.ValidatedFixedValue != null)
925                                         if (value != Context.Element.ValidatedFixedValue)
926                                                 HandleError ("Fixed value constraint was not satisfied.");
927                                 ret = AssessStringValid (st, dt, value);
928                         }
929
930 #region Key Constraints
931                         if (!IgnoreIdentity)
932                                 ValidateSimpleContentIdentity (dt, value);
933 #endregion
934
935                         shouldValidateCharacters = false;
936
937                         if (info != null) {
938                                 info.IsNil = xsiNilDepth >= 0;
939                                 info.SchemaElement = null;
940                                 info.SchemaType = st;
941                                 if (st == null)
942                                         info.SchemaType = XmlSchemaType.GetBuiltInSimpleType (dt.TypeCode);
943                                 info.SchemaAttribute = null;
944                                 info.IsDefault = false; // FIXME: might be true
945                                 info.MemberType = null; // FIXME: check
946                                 // FIXME: supply Validity (really useful?)
947                         }
948
949                         return ret;
950                 }
951
952                 // 3.14.4 String Valid 
953                 private object AssessStringValid (SimpleType st,
954                         XsDatatype dt, string value)
955                 {
956                         XsDatatype validatedDatatype = dt;
957                         object ret = null;
958                         if (st != null) {
959                                 string normalized = validatedDatatype.Normalize (value);
960                                 string [] values;
961                                 XsDatatype itemDatatype;
962                                 SimpleType itemSimpleType;
963                                 switch (st.DerivedBy) {
964                                 case XmlSchemaDerivationMethod.List:
965                                         SimpleTypeList listContent = st.Content as SimpleTypeList;
966                                         values = normalized.Split (XmlChar.WhitespaceChars);
967                                         // LAMESPEC: Types of each element in
968                                         // the returned list might be 
969                                         // inconsistent, so basically returning 
970                                         // value does not make sense without 
971                                         // explicit runtime type information 
972                                         // for base primitive type.
973                                         object [] retValues = new object [values.Length];
974                                         itemDatatype = listContent.ValidatedListItemType as XsDatatype;
975                                         itemSimpleType = listContent.ValidatedListItemType as SimpleType;
976                                         for (int vi = 0; vi < values.Length; vi++) {
977                                                 string each = values [vi];
978                                                 if (each == String.Empty)
979                                                         continue;
980                                                 // validate against ValidatedItemType
981                                                 if (itemDatatype != null) {
982                                                         try {
983                                                                 retValues [vi] = itemDatatype.ParseValue (each, nameTable, nsResolver);
984                                                         } catch (Exception ex) { // FIXME: (wishlist) better exception handling ;-(
985                                                                 HandleError ("List type value contains one or more invalid values.", ex);
986                                                                 break;
987                                                         }
988                                                 }
989                                                 else
990                                                         AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
991                                         }
992                                         ret = retValues;
993                                         break;
994                                 case XmlSchemaDerivationMethod.Union:
995                                         SimpleTypeUnion union = st.Content as SimpleTypeUnion;
996                                         {
997                                                 string each = normalized;
998                                                 // validate against ValidatedItemType
999                                                 bool passed = false;
1000                                                 foreach (object eachType in union.ValidatedTypes) {
1001                                                         itemDatatype = eachType as XsDatatype;
1002                                                         itemSimpleType = eachType as SimpleType;
1003                                                         if (itemDatatype != null) {
1004                                                                 try {
1005                                                                         ret = itemDatatype.ParseValue (each, nameTable, nsResolver);
1006                                                                 } catch (Exception) { // FIXME: (wishlist) better exception handling ;-(
1007                                                                         continue;
1008                                                                 }
1009                                                         }
1010                                                         else {
1011                                                                 try {
1012                                                                         ret = AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
1013                                                                 } catch (ValException) {
1014                                                                         continue;
1015                                                                 }
1016                                                         }
1017                                                         passed = true;
1018                                                         break;
1019                                                 }
1020                                                 if (!passed) {
1021                                                         HandleError ("Union type value contains one or more invalid values.");
1022                                                         break;
1023                                                 }
1024                                         }
1025                                         break;
1026                                 case XmlSchemaDerivationMethod.Restriction:
1027                                         SimpleTypeRest str = st.Content as SimpleTypeRest;
1028                                         // facet validation
1029                                         if (str != null) {
1030                                                 /* Don't forget to validate against inherited type's facets 
1031                                                  * Could we simplify this by assuming that the basetype will also
1032                                                  * be restriction?
1033                                                  * */
1034                                                  // mmm, will check later.
1035                                                 SimpleType baseType = st.BaseXmlSchemaType as SimpleType;
1036                                                 if (baseType != null) {
1037                                                          ret = AssessStringValid (baseType, dt, normalized);
1038                                                 }
1039                                                 if (!str.ValidateValueWithFacets (normalized, nameTable)) {
1040                                                         HandleError ("Specified value was invalid against the facets.");
1041                                                         break;
1042                                                 }
1043                                         }
1044                                         validatedDatatype = st.Datatype;
1045                                         break;
1046                                 }
1047                         }
1048                         if (validatedDatatype != null) {
1049                                 try {
1050                                         ret = validatedDatatype.ParseValue (value, nameTable, nsResolver);
1051                                 } catch (Exception ex) {        // FIXME: (wishlist) It is bad manner ;-(
1052                                         HandleError (String.Format ("Invalidly typed data was specified."), ex);
1053                                 }
1054                         }
1055                         return ret;
1056                 }
1057
1058                 #endregion
1059
1060                 #region Key Constraints Validation
1061                 private XsdKeyTable CreateNewKeyTable (XmlSchemaIdentityConstraint ident)
1062                 {
1063                         XsdKeyTable seq = new XsdKeyTable (ident);
1064                         seq.StartDepth = depth;
1065                         this.keyTables.Add (seq);
1066                         return seq;
1067                 }
1068
1069                 // 3.11.4 Identity Constraint Satisfied
1070                 private void ValidateKeySelectors ()
1071                 {
1072                         if (tmpKeyrefPool != null)
1073                                 tmpKeyrefPool.Clear ();
1074                         if (Context.Element != null && Context.Element.Constraints.Count > 0) {
1075                                 // (a) Create new key sequences, if required.
1076                                 for (int i = 0; i < Context.Element.Constraints.Count; i++) {
1077                                         XmlSchemaIdentityConstraint ident = (XmlSchemaIdentityConstraint) Context.Element.Constraints [i];
1078                                         XsdKeyTable seq = CreateNewKeyTable (ident);
1079                                         if (ident is XmlSchemaKeyref) {
1080                                                 if (tmpKeyrefPool == null)
1081                                                         tmpKeyrefPool = new ArrayList ();
1082                                                 tmpKeyrefPool.Add (seq);
1083                                         }
1084                                 }
1085                         }
1086
1087                         // (b) Evaluate current key sequences.
1088                         for (int i = 0; i < keyTables.Count; i++) {
1089                                 XsdKeyTable seq  = (XsdKeyTable) keyTables [i];
1090                                 if (seq.SelectorMatches (this.elementQNameStack, depth) != null) {
1091                                         // creates and registers new entry.
1092                                         XsdKeyEntry entry = new XsdKeyEntry (seq, depth, lineInfo);
1093                                         seq.Entries.Add (entry);
1094                                 }
1095                         }
1096                 }
1097
1098                 private void ValidateKeyFields (bool isAttr, bool isNil, object schemaType, string attrName, string attrNs, XmlValueGetter getter)
1099                 {
1100                         // (c) Evaluate field paths.
1101                         for (int i = 0; i < keyTables.Count; i++) {
1102                                 XsdKeyTable seq  = (XsdKeyTable) keyTables [i];
1103                                 // If possible, create new field entry candidates.
1104                                 for (int j = 0; j < seq.Entries.Count; j++) {
1105                                         try {
1106                                                 seq.Entries [j].ProcessMatch (
1107                                                         isAttr,
1108                                                         elementQNameStack,
1109                                                         nominalEventSender,
1110                                                         nameTable,
1111                                                         BaseUri,
1112                                                         schemaType,
1113                                                         nsResolver,
1114                                                         lineInfo,
1115                                                         depth,
1116                                                         attrName,
1117                                                         attrNs,
1118                                                         getter == null ?
1119                                                                 null :
1120                                                                 getter (),
1121                                                         isNil, 
1122                                                         currentKeyFieldConsumers);
1123                                         } catch (ValException ex) {
1124                                                 HandleError (ex);
1125                                         }
1126                                 }
1127                         }
1128                 }
1129
1130                 private void ProcessKeyEntryOne (XsdKeyEntry entry, bool isAttr, bool isNil, object schemaType, string attrName, string attrNs, XmlValueGetter getter)
1131                 {
1132                 }
1133
1134                 private void ValidateEndElementKeyConstraints ()
1135                 {
1136                         // Reset Identity constraints.
1137                         for (int i = 0; i < keyTables.Count; i++) {
1138                                 XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
1139                                 if (seq.StartDepth == depth) {
1140                                         ValidateEndKeyConstraint (seq);
1141                                 } else {
1142                                         for (int k = 0; k < seq.Entries.Count; k++) {
1143                                                 XsdKeyEntry entry = seq.Entries [k] as XsdKeyEntry;
1144                                                 // Remove finished (maybe key not found) entries.
1145                                                 if (entry.StartDepth == depth) {
1146                                                         if (entry.KeyFound)
1147                                                                 seq.FinishedEntries.Add (entry);
1148                                                         else if (seq.SourceSchemaIdentity is XmlSchemaKey)
1149                                                                 HandleError ("Key sequence is missing.");
1150                                                         seq.Entries.RemoveAt (k);
1151                                                         k--;
1152                                                 }
1153                                                 // Pop validated key depth to find two or more fields.
1154                                                 else {
1155                                                         for (int j = 0; j < entry.KeyFields.Count; j++) {
1156                                                                 XsdKeyEntryField kf = entry.KeyFields [j];
1157                                                                 if (!kf.FieldFound && kf.FieldFoundDepth == depth) {
1158                                                                         kf.FieldFoundDepth = 0;
1159                                                                         kf.FieldFoundPath = null;
1160                                                                 }
1161                                                         }
1162                                                 }
1163                                         }
1164                                 }
1165                         }
1166                         for (int i = 0; i < keyTables.Count; i++) {
1167                                 XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
1168                                 if (seq.StartDepth == depth) {
1169                                         keyTables.RemoveAt (i);
1170                                         i--;
1171                                 }
1172                         }
1173                 }
1174
1175                 private void ValidateEndKeyConstraint (XsdKeyTable seq)
1176                 {
1177                         ArrayList errors = new ArrayList ();
1178                         for (int i = 0; i < seq.Entries.Count; i++) {
1179                                 XsdKeyEntry entry = (XsdKeyEntry) seq.Entries [i];
1180                                 if (entry.KeyFound)
1181                                         continue;
1182                                 if (seq.SourceSchemaIdentity is XmlSchemaKey)
1183                                         errors.Add ("line " + entry.SelectorLineNumber + "position " + entry.SelectorLinePosition);
1184                         }
1185                         if (errors.Count > 0)
1186                                 HandleError ("Invalid identity constraints were found. Key was not found. "
1187                                         + String.Join (", ", errors.ToArray (typeof (string)) as string []));
1188
1189                         errors.Clear ();
1190                         // Find reference target
1191                         XmlSchemaKeyref xsdKeyref = seq.SourceSchemaIdentity as XmlSchemaKeyref;
1192                         if (xsdKeyref != null) {
1193                                 for (int i = this.keyTables.Count - 1; i >= 0; i--) {
1194                                         XsdKeyTable target = this.keyTables [i] as XsdKeyTable;
1195                                         if (target.SourceSchemaIdentity == xsdKeyref.Target) {
1196                                                 seq.ReferencedKey = target;
1197                                                 for (int j = 0; j < seq.FinishedEntries.Count; j++) {
1198                                                         XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [j];
1199                                                         for (int k = 0; k < target.FinishedEntries.Count; k++) {
1200                                                                 XsdKeyEntry targetEntry = (XsdKeyEntry) target.FinishedEntries [k];
1201                                                                 if (entry.CompareIdentity (targetEntry)) {
1202                                                                         entry.KeyRefFound = true;
1203                                                                         break;
1204                                                                 }
1205                                                         }
1206                                                 }
1207                                         }
1208                                 }
1209                                 if (seq.ReferencedKey == null)
1210                                         HandleError ("Target key was not found.");
1211                                 for (int i = 0; i < seq.FinishedEntries.Count; i++) {
1212                                         XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [i];
1213                                         if (!entry.KeyRefFound)
1214                                                 errors.Add (" line " + entry.SelectorLineNumber + ", position " + entry.SelectorLinePosition);
1215                                 }
1216                                 if (errors.Count > 0)
1217                                         HandleError ("Invalid identity constraints were found. Referenced key was not found: "
1218                                                 + String.Join (" / ", errors.ToArray (typeof (string)) as string []));
1219                         }
1220                 }
1221
1222                 private void ValidateSimpleContentIdentity (
1223                         XmlSchemaDatatype dt, string value)
1224                 {
1225                         // Identity field value
1226                         if (currentKeyFieldConsumers != null) {
1227                                 while (this.currentKeyFieldConsumers.Count > 0) {
1228                                         XsdKeyEntryField field = this.currentKeyFieldConsumers [0] as XsdKeyEntryField;
1229                                         if (field.Identity != null)
1230                                                 HandleError ("Two or more identical field was found. Former value is '" + field.Identity + "' .");
1231                                         object identity = null; // This means empty value
1232                                         if (dt != null) {
1233                                                 try {
1234                                                         identity = dt.ParseValue (value, nameTable, nsResolver);
1235                                                 } catch (Exception ex) { // FIXME: (wishlist) This is bad manner ;-(
1236                                                         HandleError ("Identity value is invalid against its data type " + dt.TokenizedType, ex);
1237                                                 }
1238                                         }
1239                                         if (identity == null)
1240                                                 identity = value;
1241
1242                                         if (!field.SetIdentityField (identity, depth == xsiNilDepth, dt as XsdAnySimpleType, depth, lineInfo))
1243                                                 HandleError ("Two or more identical key value was found: '" + value + "' .");
1244                                         this.currentKeyFieldConsumers.RemoveAt (0);
1245                                 }
1246                         }
1247                 }
1248                 #endregion
1249
1250                 #region xsi:type
1251                 private object GetXsiType (string name)
1252                 {
1253                         object xsiType = null;
1254                         XmlQualifiedName typeQName =
1255                                 XmlQualifiedName.Parse (name, nsResolver);
1256                         if (typeQName == ComplexType.AnyTypeName)
1257                                 xsiType = ComplexType.AnyType;
1258                         else if (XmlSchemaUtil.IsBuiltInDatatypeName (typeQName))
1259                                 xsiType = XsDatatype.FromName (typeQName);
1260                         else
1261                                 xsiType = FindType (typeQName);
1262                         return xsiType;
1263                 }
1264
1265                 private void HandleXsiType (string typename)
1266                 {
1267                         XsElement element = Context.Element;
1268                         object xsiType = GetXsiType (typename);
1269                         if (xsiType == null) {
1270                                 HandleError ("The instance type was not found: " + typename);
1271                                 return;
1272                         }
1273                         XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
1274                         if (xsiSchemaType != null && Context.Element != null) {
1275                                 XmlSchemaType elemBaseType = element.ElementType as XmlSchemaType;
1276                                 if (elemBaseType != null && (xsiSchemaType.DerivedBy & elemBaseType.FinalResolved) != 0)
1277                                         HandleError ("The instance type is prohibited by the type of the context element.");
1278                                 if (elemBaseType != xsiType && (xsiSchemaType.DerivedBy & element.BlockResolved) != 0)
1279                                         HandleError ("The instance type is prohibited by the context element.");
1280                         }
1281                         ComplexType xsiComplexType = xsiType as ComplexType;
1282                         if (xsiComplexType != null && xsiComplexType.IsAbstract)
1283                                 HandleError ("The instance type is abstract: " + typename);
1284                         else {
1285                                 // If current schema type exists, then this xsi:type must be
1286                                 // valid extension of that type. See 1.2.1.2.4.
1287                                 if (element != null) {
1288                                         AssessLocalTypeDerivationOK (xsiType, element.ElementType, element.BlockResolved);
1289                                 }
1290                                 // See also ValidateEndOfAttributes().
1291                                 Context.XsiType = xsiType;
1292                         }
1293                 }
1294
1295                 // It is common to ElementLocallyValid::4 and SchemaValidityAssessment::1.2.1.2.4
1296                 private void AssessLocalTypeDerivationOK (object xsiType, object baseType, XmlSchemaDerivationMethod flag)
1297                 {
1298                         XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
1299                         ComplexType baseComplexType = baseType as ComplexType;
1300                         ComplexType xsiComplexType = xsiSchemaType as ComplexType;
1301                         if (xsiType != baseType) {
1302                                 // Extracted (not extraneous) check for 3.4.6 TypeDerivationOK.
1303                                 if (baseComplexType != null)
1304                                         flag |= baseComplexType.BlockResolved;
1305                                 if (flag == XmlSchemaDerivationMethod.All) {
1306                                         HandleError ("Prohibited element type substitution.");
1307                                         return;
1308                                 } else if (xsiSchemaType != null && (flag & xsiSchemaType.DerivedBy) != 0) {
1309                                         HandleError ("Prohibited element type substitution.");
1310                                         return;
1311                                 }
1312                         }
1313
1314                         if (xsiComplexType != null)
1315                                 try {
1316                                         xsiComplexType.ValidateTypeDerivationOK (baseType, null, null);
1317                                 } catch (ValException ex) {
1318                                         HandleError (ex);
1319                                 }
1320                         else {
1321                                 SimpleType xsiSimpleType = xsiType as SimpleType;
1322                                 if (xsiSimpleType != null) {
1323                                         try {
1324                                                 xsiSimpleType.ValidateTypeDerivationOK (baseType, null, null, true);
1325                                         } catch (ValException ex) {
1326                                                 HandleError (ex);
1327                                         }
1328                                 }
1329                                 else if (xsiType is XsDatatype) {
1330                                         // do nothing
1331                                 }
1332                                 else
1333                                         HandleError ("Primitive data type cannot be derived type using xsi:type specification.");
1334                         }
1335                 }
1336                 #endregion
1337
1338                 private void HandleXsiNil (string value, XmlSchemaInfo info)
1339                 {
1340                         XsElement element = Context.Element;
1341                         if (!element.ActualIsNillable) {
1342                                 HandleError (String.Format ("Current element '{0}' is not nillable and thus does not allow occurence of 'nil' attribute.", Context.Element.QualifiedName));
1343                                 return;
1344                         }
1345                         value = value.Trim (XmlChar.WhitespaceChars);
1346                         // 3.2.
1347                         // Note that 3.2.1 xsi:nil constraints are to be 
1348                         // validated in AssessElementSchemaValidity() and 
1349                         // ValidateCharacters().
1350                         if (value == "true") {
1351                                 if (element.ValidatedFixedValue != null)
1352                                         HandleError ("Schema instance nil was specified, where the element declaration for " + element.QualifiedName + "has fixed value constraints.");
1353                                 xsiNilDepth = depth;
1354                                 if (info != null)
1355                                         info.IsNil = true;
1356                         }
1357                 }
1358
1359                 #region External schema resolution
1360
1361                 private XmlSchema ReadExternalSchema (string uri)
1362                 {
1363                         Uri absUri = new Uri (SourceUri, uri.Trim (XmlChar.WhitespaceChars));
1364                         XmlTextReader xtr = null;
1365                         try {
1366                                 xtr = new XmlTextReader (absUri.ToString (),
1367                                         (Stream) xmlResolver.GetEntity (
1368                                                 absUri, null, typeof (Stream)),
1369                                         nameTable);
1370                                 return XmlSchema.Read (
1371                                         xtr, ValidationEventHandler);
1372                         } finally {
1373                                 if (xtr != null)
1374                                         xtr.Close ();
1375                         }
1376                 }
1377
1378                 private void HandleSchemaLocation (string schemaLocation)
1379                 {
1380                         if (xmlResolver == null)
1381                                 return;
1382                         XmlSchema schema = null;
1383                         bool schemaAdded = false;
1384                         string [] tmp = null;
1385                         try {
1386                                 schemaLocation = XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.Token).Datatype.ParseValue (schemaLocation, null, null) as string;
1387                                 tmp = schemaLocation.Split (XmlChar.WhitespaceChars);
1388                         } catch (Exception ex) {
1389                                 HandleError ("Invalid schemaLocation attribute format.", ex, true);
1390                                 tmp = new string [0];
1391                         }
1392                         if (tmp.Length % 2 != 0)
1393                                 HandleError ("Invalid schemaLocation attribute format.");
1394                         for (int i = 0; i < tmp.Length; i += 2) {
1395                                 try {
1396                                         schema = ReadExternalSchema (tmp [i + 1]);
1397                                 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
1398                                         HandleError ("Could not resolve schema location URI: " + schemaLocation, ex, true);
1399                                         continue;
1400                                 }
1401                                 if (schema.TargetNamespace == null)
1402                                         schema.TargetNamespace = tmp [i];
1403                                 else if (schema.TargetNamespace != tmp [i])
1404                                         HandleError ("Specified schema has different target namespace.");
1405
1406                                 if (schema != null) {
1407                                         if (!schemas.Contains (schema.TargetNamespace)) {
1408                                                 schemaAdded = true;
1409                                                 schemas.Add (schema);
1410                                         }
1411                                 }
1412                         }
1413                         if (schemaAdded)
1414                                 schemas.Compile ();
1415                 }
1416
1417                 private void HandleNoNSSchemaLocation (string noNsSchemaLocation)
1418                 {
1419                         if (xmlResolver == null)
1420                                 return;
1421                         XmlSchema schema = null;
1422                         bool schemaAdded = false;
1423
1424                         try {
1425                                 schema = ReadExternalSchema (noNsSchemaLocation);
1426                         } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
1427                                 HandleError ("Could not resolve schema location URI: " + noNsSchemaLocation, ex, true);
1428                         }
1429                         if (schema != null && schema.TargetNamespace != null)
1430                                 HandleError ("Specified schema has different target namespace.");
1431
1432                         if (schema != null) {
1433                                 if (!schemas.Contains (schema.TargetNamespace)) {
1434                                         schemaAdded = true;
1435                                         schemas.Add (schema);
1436                                 }
1437                         }
1438                         if (schemaAdded)
1439                                 schemas.Compile ();
1440                 }
1441
1442                 #endregion
1443         }
1444 }
1445
1446 #endif