2 // Mono.Xml.Schema.XsdValidatingReader.cs
5 // Atsushi Enomoto (ginga@kit.hi-ho.ne.jp)
7 // (C)2003 Atsushi Enomoto
11 // This class doesn't support set_XmlResolver, since it isn't common to XmlReader interface.
12 // Try to set that of xml reader which is used to construct this object.
16 // Permission is hereby granted, free of charge, to any person obtaining
17 // a copy of this software and associated documentation files (the
18 // "Software"), to deal in the Software without restriction, including
19 // without limitation the rights to use, copy, modify, merge, publish,
20 // distribute, sublicense, and/or sell copies of the Software, and to
21 // permit persons to whom the Software is furnished to do so, subject to
22 // the following conditions:
24 // The above copyright notice and this permission notice shall be
25 // included in all copies or substantial portions of the Software.
27 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
31 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
32 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36 using System.Collections;
37 using System.Collections.Specialized;
40 using System.Xml.Schema;
43 namespace Mono.Xml.Schema
45 internal class XsdValidatingReader : XmlReader, IXmlLineInfo, IHasXmlSchemaInfo, IHasXmlParserContext, IXmlNamespaceResolver
47 static char [] wsChars = new char [] {' ', '\t', '\n', '\r'};
51 IHasXmlSchemaInfo sourceReaderSchemaInfo;
52 IXmlLineInfo readerLineInfo;
53 // bool laxElementValidation = true;
54 ValidationType validationType;
55 XmlSchemaSet schemas = new XmlSchemaSet ();
56 bool namespaces = true;
58 bool checkIdentity = true;
59 Hashtable idList = new Hashtable ();
60 ArrayList missingIDReferences;
63 ArrayList keyTables = new ArrayList ();
64 ArrayList currentKeyFieldConsumers;
66 XsdValidationStateManager stateManager = new XsdValidationStateManager ();
67 XsdValidationContext context = new XsdValidationContext ();
68 XsdValidationState childParticleState;
71 StringBuilder storedCharacters = new StringBuilder ();
72 bool shouldValidateCharacters;
73 int skipValidationDepth = -1;
75 XmlSchemaAttribute [] defaultAttributes = new XmlSchemaAttribute [0];
76 int currentDefaultAttribute = -1;
77 XmlQualifiedName currentQName;
79 ArrayList elementQNameStack = new ArrayList ();
83 bool defaultAttributeConsumed;
85 // Validation engine cached object
86 ArrayList defaultAttributesCache = new ArrayList ();
87 ArrayList tmpKeyrefPool;
90 public XsdValidatingReader (XmlReader reader)
93 readerLineInfo = reader as IXmlLineInfo;
94 sourceReaderSchemaInfo = reader as IHasXmlSchemaInfo;
98 public ValidationEventHandler ValidationEventHandler;
100 // Private Properties
101 private XmlQualifiedName CurrentQName {
103 if (currentQName == null)
104 currentQName = new XmlQualifiedName (LocalName, NamespaceURI);
109 internal ArrayList CurrentKeyFieldConsumers {
111 if (currentKeyFieldConsumers == null)
112 currentKeyFieldConsumers = new ArrayList ();
113 return currentKeyFieldConsumers;
117 private ArrayList MissingIDReferences {
119 if (missingIDReferences == null)
120 missingIDReferences = new ArrayList ();
121 return missingIDReferences;
125 // Public Non-overrides
127 public int XsiNilDepth {
128 get { return xsiNilDepth; }
131 public bool Namespaces {
132 get { return namespaces; }
133 set { namespaces = value; }
136 public XmlReader Reader {
137 get { return reader; }
140 // This is required to resolve xsi:schemaLocation
141 public XmlResolver XmlResolver {
147 // This should be changed before the first Read() call.
148 public XmlSchemaSet Schemas {
149 get { return schemas; }
151 if (ReadState != ReadState.Initial)
152 throw new InvalidOperationException ("Schemas must be set before the first call to Read().");
157 public object SchemaType {
159 if (ReadState != ReadState.Interactive)
163 case XmlNodeType.Element:
164 if (context.ActualType != null)
165 return context.ActualType;
166 else if (context.Element != null)
167 return context.Element.ElementType;
169 return SourceReaderSchemaType;
170 case XmlNodeType.Attribute:
171 XmlSchemaComplexType ct = context.ActualType as XmlSchemaComplexType;
173 XmlSchemaAttribute attdef = ct.AttributeUses [CurrentQName] as XmlSchemaAttribute;
175 return attdef.AttributeType;
177 return SourceReaderSchemaType;
179 return SourceReaderSchemaType;
184 private object SourceReaderSchemaType {
185 get { return this.sourceReaderSchemaInfo != null ? sourceReaderSchemaInfo.SchemaType : null; }
188 public ValidationType ValidationType {
189 get { return validationType; }
191 if (ReadState != ReadState.Initial)
192 throw new InvalidOperationException ("ValidationType must be set before reading.");
193 validationType = value;
197 IDictionary IXmlNamespaceResolver.GetNamespacesInScope (XmlNamespaceScope scope)
199 IXmlNamespaceResolver resolver = reader as IXmlNamespaceResolver;
200 if (resolver == null)
201 throw new NotSupportedException ("The input XmlReader does not implement IXmlNamespaceResolver and thus this validating reader cannot collect in-scope namespaces.");
202 return resolver.GetNamespacesInScope (scope);
205 string IXmlNamespaceResolver.LookupPrefix (string ns)
207 return ((IXmlNamespaceResolver) this).LookupPrefix (ns, false);
210 string IXmlNamespaceResolver.LookupPrefix (string ns, bool atomizedNames)
212 IXmlNamespaceResolver resolver = reader as IXmlNamespaceResolver;
213 if (resolver == null)
214 throw new NotSupportedException ("The input XmlReader does not implement IXmlNamespaceResolver and thus this validating reader cannot execute namespace prefix lookup.");
215 return resolver.LookupPrefix (ns, atomizedNames);
218 // It is used only for independent XmlReader use, not for XmlValidatingReader.
220 public override object ReadTypedValue ()
222 public object ReadTypedValue ()
225 XmlSchemaDatatype dt = SchemaType as XmlSchemaDatatype;
226 XmlSchemaSimpleType st = SchemaType as XmlSchemaSimpleType;
233 case XmlNodeType.Element:
237 storedCharacters.Length = 0;
242 case XmlNodeType.SignificantWhitespace:
243 case XmlNodeType.Text:
244 case XmlNodeType.CDATA:
245 storedCharacters.Append (Value);
247 case XmlNodeType.Comment:
253 } while (loop && !EOF && ReadState == ReadState.Interactive);
254 return dt.ParseValue (storedCharacters.ToString (), NameTable, ParserContext.NamespaceManager);
255 case XmlNodeType.Attribute:
256 return dt.ParseValue (Value, NameTable, ParserContext.NamespaceManager);
261 // Public Overrided Properties
263 public override int AttributeCount {
265 return reader.AttributeCount + defaultAttributes.Length;
269 public override string BaseURI {
270 get { return reader.BaseURI; }
273 // If this class is used to implement XmlValidatingReader,
274 // it should be left to DTDValidatingReader. In other cases,
275 // it depends on the reader's ability.
276 public override bool CanResolveEntity {
277 get { return reader.CanResolveEntity; }
280 public override int Depth {
282 if (currentDefaultAttribute < 0)
284 if (this.defaultAttributeConsumed)
285 return reader.Depth + 2;
286 return reader.Depth + 1;
290 public override bool EOF {
291 get { return reader.EOF; }
294 public override bool HasValue {
296 if (currentDefaultAttribute < 0)
297 return reader.HasValue;
302 public override bool IsDefault {
304 if (currentDefaultAttribute < 0)
305 return reader.IsDefault;
310 public override bool IsEmptyElement {
312 if (currentDefaultAttribute < 0)
313 return reader.IsEmptyElement;
318 public override string this [int i] {
319 get { return GetAttribute (i); }
322 public override string this [string name] {
323 get { return GetAttribute (name); }
326 public override string this [string localName, string ns] {
327 get { return GetAttribute (localName, ns); }
330 int IXmlLineInfo.LineNumber {
331 get { return readerLineInfo != null ? readerLineInfo.LineNumber : 0; }
334 int IXmlLineInfo.LinePosition {
335 get { return readerLineInfo != null ? readerLineInfo.LinePosition : 0; }
338 public override string LocalName {
340 if (currentDefaultAttribute < 0)
341 return reader.LocalName;
342 if (defaultAttributeConsumed)
344 return defaultAttributes [currentDefaultAttribute].QualifiedName.Name;
348 public override string Name {
350 if (currentDefaultAttribute < 0)
352 if (defaultAttributeConsumed)
355 XmlQualifiedName qname = defaultAttributes [currentDefaultAttribute].QualifiedName;
356 string prefix = Prefix;
357 if (prefix == String.Empty)
360 return String.Concat (prefix, ":", qname.Name);
364 public override string NamespaceURI {
366 if (currentDefaultAttribute < 0)
367 return reader.NamespaceURI;
368 if (defaultAttributeConsumed)
370 return defaultAttributes [currentDefaultAttribute].QualifiedName.Namespace;
374 public override XmlNameTable NameTable {
375 get { return reader.NameTable; }
378 public override XmlNodeType NodeType {
380 if (currentDefaultAttribute < 0)
381 return reader.NodeType;
382 if (defaultAttributeConsumed)
383 return XmlNodeType.Text;
384 return XmlNodeType.Attribute;
388 public XmlParserContext ParserContext {
389 get { return XmlSchemaUtil.GetParserContext (reader); }
392 public override string Prefix {
394 if (currentDefaultAttribute < 0)
395 return reader.Prefix;
396 if (defaultAttributeConsumed)
398 XmlQualifiedName qname = defaultAttributes [currentDefaultAttribute].QualifiedName;
399 string prefix = this.ParserContext.NamespaceManager.LookupPrefix (qname.Namespace, false);
407 public override char QuoteChar {
408 get { return reader.QuoteChar; }
411 public override ReadState ReadState {
412 get { return reader.ReadState; }
415 public override string Value {
417 if (currentDefaultAttribute < 0)
419 string value = defaultAttributes [currentDefaultAttribute].ValidatedDefaultValue;
421 value = defaultAttributes [currentDefaultAttribute].ValidatedFixedValue;
426 public override string XmlLang {
428 string xmlLang = reader.XmlLang;
431 int idx = this.FindDefaultAttribute ("lang", XmlNamespaceManager.XmlnsXml);
434 xmlLang = defaultAttributes [idx].ValidatedDefaultValue;
436 xmlLang = defaultAttributes [idx].ValidatedFixedValue;
441 public override XmlSpace XmlSpace {
443 XmlSpace space = reader.XmlSpace;
444 if (space != XmlSpace.None)
446 int idx = this.FindDefaultAttribute ("space", XmlNamespaceManager.XmlnsXml);
448 return XmlSpace.None;
449 string spaceSpec = defaultAttributes [idx].ValidatedDefaultValue;
450 if (spaceSpec == null)
451 spaceSpec = defaultAttributes [idx].ValidatedFixedValue;
452 return (XmlSpace) Enum.Parse (typeof (XmlSpace), spaceSpec, false);
458 private XmlQualifiedName QualifyName (string name)
460 return XmlQualifiedName.Parse (name, this);
463 private void HandleError (string error)
465 HandleError (error, null);
468 private void HandleError (string error, Exception innerException)
470 HandleError (error, innerException, false);
473 private void HandleError (string error, Exception innerException, bool isWarning)
475 if (ValidationType == ValidationType.None) // extra quick check
478 XmlSchemaException schemaException = new XmlSchemaException (error,
479 this, this.BaseURI, null, innerException);
480 HandleError (schemaException, isWarning);
483 private void HandleError (XmlSchemaException schemaException)
485 HandleError (schemaException, false);
488 private void HandleError (XmlSchemaException schemaException, bool isWarning)
490 if (ValidationType == ValidationType.None)
493 ValidationEventArgs e = new ValidationEventArgs (schemaException,
494 schemaException.Message, isWarning ? XmlSeverityType.Warning : XmlSeverityType.Error);
496 if (ValidationEventHandler != null)
497 ValidationEventHandler (this, e);
499 else if (e.Severity == XmlSeverityType.Error)
503 private XmlSchemaElement FindElement (string name, string ns)
505 return (XmlSchemaElement) schemas.GlobalElements [new XmlQualifiedName (name, ns)];
508 private XmlSchemaType FindType (XmlQualifiedName qname)
510 return (XmlSchemaType) schemas.GlobalTypes [qname];
513 private void ValidateStartElementParticle ()
515 stateManager.CurrentElement = null;
516 context.ParticleState = context.ParticleState.EvaluateStartElement (reader.LocalName, reader.NamespaceURI);
517 if (context.ParticleState == XsdValidationState.Invalid)
518 HandleError ("Invalid start element: " + reader.NamespaceURI + ":" + reader.LocalName);
520 context.Element = stateManager.CurrentElement;
521 if (context.Element != null)
522 context.SchemaType = context.Element.ElementType;
525 private void ValidateEndElementParticle ()
527 if (childParticleState != null) {
528 if (!childParticleState.EvaluateEndElement ()) {
529 HandleError ("Invalid end element: " + reader.Name);
532 context.PopScope (reader.Depth);
535 // Utility for missing validation completion related to child items.
536 private void ValidateCharacters ()
538 if (xsiNilDepth >= 0 && xsiNilDepth < reader.Depth)
539 HandleError ("Element item appeared, while current element context is nil.");
541 storedCharacters.Append (reader.Value);
544 // Utility for missing validation completion related to child items.
545 private void ValidateEndCharacters ()
547 if (context.ActualType == null)
550 string value = storedCharacters.ToString ();
552 if (storedCharacters.Length == 0) {
553 // 3.3.4 Element Locally Valid (Element) 5.1.2
554 if (context.Element != null) {
555 if (context.Element.ValidatedDefaultValue != null)
556 value = context.Element.ValidatedDefaultValue;
560 XmlSchemaDatatype dt = context.ActualType as XmlSchemaDatatype;
561 XmlSchemaSimpleType st = context.ActualType as XmlSchemaSimpleType;
566 XmlSchemaComplexType ct = context.ActualType as XmlSchemaComplexType;
568 switch (ct.ContentType) {
569 case XmlSchemaContentType.ElementOnly:
570 case XmlSchemaContentType.Empty:
571 if (storedCharacters.Length > 0)
572 HandleError ("Character content not allowed.");
578 // 3.3.4 Element Locally Valid (Element) :: 5.2.2.2. Fixed value constraints
579 if (context.Element != null && context.Element.ValidatedFixedValue != null)
580 if (value != context.Element.ValidatedFixedValue)
581 HandleError ("Fixed value constraint was not satisfied.");
582 AssessStringValid (st, dt, value);
585 // Identity field value
586 if (currentKeyFieldConsumers != null) {
587 while (this.currentKeyFieldConsumers.Count > 0) {
588 XsdKeyEntryField field = this.currentKeyFieldConsumers [0] as XsdKeyEntryField;
589 if (field.Identity != null)
590 HandleError ("Two or more identical field was found. Former value is '" + field.Identity + "' .");
591 object identity = null; // This means empty value
594 identity = dt.ParseValue (value, NameTable, ParserContext.NamespaceManager);
595 } catch (Exception ex) { // FIXME: (wishlist) This is bad manner ;-(
596 HandleError ("Identity value is invalid against its data type " + dt.TokenizedType, ex);
599 if (identity == null)
602 if (!field.SetIdentityField (identity, reader.Depth == xsiNilDepth, dt as XsdAnySimpleType, this))
603 HandleError ("Two or more identical key value was found: '" + value + "' .");
604 this.currentKeyFieldConsumers.RemoveAt (0);
608 shouldValidateCharacters = false;
611 // 3.14.4 String Valid
612 private void AssessStringValid (XmlSchemaSimpleType st,
613 XmlSchemaDatatype dt, string value)
615 XmlSchemaDatatype validatedDatatype = dt;
617 string normalized = validatedDatatype.Normalize (value);
619 XmlSchemaDatatype itemDatatype;
620 XmlSchemaSimpleType itemSimpleType;
621 switch (st.DerivedBy) {
622 case XmlSchemaDerivationMethod.List:
623 XmlSchemaSimpleTypeList listContent = st.Content as XmlSchemaSimpleTypeList;
624 values = normalized.Split (wsChars);
625 itemDatatype = listContent.ValidatedListItemType as XmlSchemaDatatype;
626 itemSimpleType = listContent.ValidatedListItemType as XmlSchemaSimpleType;
627 for (int vi = 0; vi < values.Length; vi++) {
628 string each = values [vi];
629 if (each == String.Empty)
631 // validate against ValidatedItemType
632 if (itemDatatype != null) {
634 itemDatatype.ParseValue (each, NameTable, ParserContext.NamespaceManager);
635 } catch (Exception ex) { // FIXME: (wishlist) better exception handling ;-(
636 HandleError ("List type value contains one or more invalid values.", ex);
641 AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
644 case XmlSchemaDerivationMethod.Union:
645 XmlSchemaSimpleTypeUnion union = st.Content as XmlSchemaSimpleTypeUnion;
647 string each = normalized;
648 // validate against ValidatedItemType
650 foreach (object eachType in union.ValidatedTypes) {
651 itemDatatype = eachType as XmlSchemaDatatype;
652 itemSimpleType = eachType as XmlSchemaSimpleType;
653 if (itemDatatype != null) {
655 itemDatatype.ParseValue (each, NameTable, ParserContext.NamespaceManager);
656 } catch (Exception) { // FIXME: (wishlist) better exception handling ;-(
662 AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
663 } catch (XmlSchemaException) {
671 HandleError ("Union type value contains one or more invalid values.");
676 case XmlSchemaDerivationMethod.Restriction:
677 XmlSchemaSimpleTypeRestriction str = st.Content as XmlSchemaSimpleTypeRestriction;
680 /* Don't forget to validate against inherited type's facets
681 * Could we simplify this by assuming that the basetype will also
684 // mmm, will check later.
685 XmlSchemaSimpleType baseType = st.BaseXmlSchemaType as XmlSchemaSimpleType;
686 if (baseType != null) {
687 AssessStringValid(baseType, dt, normalized);
689 if (!str.ValidateValueWithFacets (normalized, NameTable)) {
690 HandleError ("Specified value was invalid against the facets.");
694 validatedDatatype = st.Datatype;
698 if (validatedDatatype != null) {
700 validatedDatatype.ParseValue (value, NameTable, ParserContext.NamespaceManager);
701 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
702 HandleError ("Invalidly typed data was specified.", ex);
707 private object GetLocalTypeDefinition (string name)
709 object xsiType = null;
710 XmlQualifiedName typeQName = QualifyName (name);
711 if (typeQName == XmlSchemaComplexType.AnyTypeName)
712 xsiType = XmlSchemaComplexType.AnyType;
713 else if (XmlSchemaUtil.IsBuiltInDatatypeName (typeQName))
714 xsiType = XmlSchemaDatatype.FromName (typeQName);
716 xsiType = FindType (typeQName);
720 // It is common to ElementLocallyValid::4 and SchemaValidityAssessment::1.2.1.2.4
721 private void AssessLocalTypeDerivationOK (object xsiType, object baseType, XmlSchemaDerivationMethod flag)
723 XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
724 XmlSchemaComplexType baseComplexType = baseType as XmlSchemaComplexType;
725 XmlSchemaComplexType xsiComplexType = xsiSchemaType as XmlSchemaComplexType;
726 if (xsiType != baseType) {
727 // Extracted (not extraneous) check for 3.4.6 TypeDerivationOK.
728 if (baseComplexType != null)
729 flag |= baseComplexType.BlockResolved;
730 if (flag == XmlSchemaDerivationMethod.All) {
731 HandleError ("Prohibited element type substitution.");
733 } else if (xsiSchemaType != null && (flag & xsiSchemaType.DerivedBy) != 0) {
734 HandleError ("Prohibited element type substitution.");
739 if (xsiComplexType != null)
741 xsiComplexType.ValidateTypeDerivationOK (baseType, null, null);
742 } catch (XmlSchemaException ex) {
743 // HandleError ("Locally specified schema complex type derivation failed. " + ex.Message, ex);
747 XmlSchemaSimpleType xsiSimpleType = xsiType as XmlSchemaSimpleType;
748 if (xsiSimpleType != null) {
750 xsiSimpleType.ValidateTypeDerivationOK (baseType, null, null, true);
751 } catch (XmlSchemaException ex) {
752 // HandleError ("Locally specified schema simple type derivation failed. " + ex.Message, ex);
756 else if (xsiType is XmlSchemaDatatype) {
760 HandleError ("Primitive data type cannot be derived type using xsi:type specification.");
764 // Section 3.3.4 of the spec.
765 private void AssessStartElementSchemaValidity ()
767 // If the reader is inside xsi:nil (and failed on validation),
768 // then simply skip its content.
769 if (xsiNilDepth >= 0 && xsiNilDepth < reader.Depth)
770 HandleError ("Element item appeared, while current element context is nil.");
772 context.Load (reader.Depth);
773 if (childParticleState != null) {
774 context.ParticleState = childParticleState;
775 childParticleState = null;
778 // If validation state exists, then first assess particle validity.
779 context.SchemaType = null;
780 if (context.ParticleState != null) {
781 ValidateStartElementParticle ();
784 string xsiNilValue = reader.GetAttribute ("nil", XmlSchema.InstanceNamespace);
785 if (xsiNilValue != null)
786 xsiNilValue = xsiNilValue.Trim (XmlChar.WhitespaceChars);
787 bool isXsiNil = xsiNilValue == "true";
788 if (isXsiNil && this.xsiNilDepth < 0)
789 xsiNilDepth = reader.Depth;
791 // [Schema Validity Assessment (Element) 1.2]
792 // Evaluate "local type definition" from xsi:type.
793 // (See spec 3.3.4 Schema Validity Assessment (Element) 1.2.1.2.3.
794 // Note that Schema Validity Assessment(Element) 1.2 takes
795 // precedence than 1.1 of that.
797 string xsiTypeName = reader.GetAttribute ("type", XmlSchema.InstanceNamespace);
798 if (xsiTypeName != null) {
799 xsiTypeName = xsiTypeName.Trim (XmlChar.WhitespaceChars);
800 object xsiType = GetLocalTypeDefinition (xsiTypeName);
802 HandleError ("The instance type was not found: " + xsiTypeName + " .");
804 XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
805 if (xsiSchemaType != null && this.context.Element != null) {
806 XmlSchemaType elemBaseType = context.Element.ElementType as XmlSchemaType;
807 if (elemBaseType != null && (xsiSchemaType.DerivedBy & elemBaseType.FinalResolved) != 0)
808 HandleError ("The instance type is prohibited by the type of the context element.");
809 if (elemBaseType != xsiType && (xsiSchemaType.DerivedBy & this.context.Element.BlockResolved) != 0)
810 HandleError ("The instance type is prohibited by the context element.");
812 XmlSchemaComplexType xsiComplexType = xsiType as XmlSchemaComplexType;
813 if (xsiComplexType != null && xsiComplexType.IsAbstract)
814 HandleError ("The instance type is abstract: " + xsiTypeName + " .");
816 // If current schema type exists, then this xsi:type must be
817 // valid extension of that type. See 1.2.1.2.4.
818 if (context.Element != null) {
819 AssessLocalTypeDerivationOK (xsiType, context.Element.ElementType, context.Element.BlockResolved);
821 AssessStartElementLocallyValidType (xsiType); // 1.2.2:
822 context.LocalTypeDefinition = xsiType;
827 context.LocalTypeDefinition = null;
829 // Create Validation Root, if not exist.
830 // [Schema Validity Assessment (Element) 1.1]
831 if (context.Element == null)
832 context.Element = FindElement (reader.LocalName, reader.NamespaceURI);
833 if (context.Element != null) {
834 if (xsiTypeName == null) {
835 context.SchemaType = context.Element.ElementType;
836 AssessElementLocallyValidElement (context.Element, xsiNilValue); // 1.1.2
839 switch (stateManager.ProcessContents) {
840 case XmlSchemaContentProcessing.Skip:
842 case XmlSchemaContentProcessing.Lax:
844 schema = schemas [reader.NamespaceURI];
845 if (schema != null && !schema.missedSubComponents)
846 HandleError ("Element declaration for " + reader.LocalName + " is missing.");
850 if (xsiTypeName == null &&
851 (schemas.Contains (reader.NamespaceURI) ||
852 !schemas.MissedSubComponents (reader.NamespaceURI)))
853 HandleError ("Element declaration for " + reader.LocalName + " is missing.");
858 if (stateManager.ProcessContents == XmlSchemaContentProcessing.Skip)
859 skipValidationDepth = reader.Depth;
861 // Finally, create child particle state.
862 XmlSchemaComplexType xsComplexType = SchemaType as XmlSchemaComplexType;
863 if (xsComplexType != null)
864 childParticleState = stateManager.Create (xsComplexType.ValidatableParticle);
865 else if (stateManager.ProcessContents == XmlSchemaContentProcessing.Lax)
866 childParticleState = stateManager.Create (XmlSchemaAny.AnyTypeContent);
868 childParticleState = stateManager.Create (XmlSchemaParticle.Empty);
870 AssessStartIdentityConstraints ();
872 context.PushScope (reader.Depth);
875 // 3.3.4 Element Locally Valid (Element)
876 private void AssessElementLocallyValidElement (XmlSchemaElement element, string xsiNilValue)
878 XmlQualifiedName qname = new XmlQualifiedName (reader.LocalName, reader.NamespaceURI);
881 HandleError ("Element declaration is required for " + qname);
883 if (element.ActualIsAbstract)
884 HandleError ("Abstract element declaration was specified for " + qname);
886 if (!element.ActualIsNillable && xsiNilValue != null)
887 HandleError ("This element declaration is not nillable: " + qname);
889 // Note that 3.2.1 xsi:nil constraints are to be validated in
890 else if (xsiNilValue == "true") {
891 // AssessElementSchemaValidity() and ValidateCharacters()
893 if (element.ValidatedFixedValue != null)
894 HandleError ("Schema instance nil was specified, where the element declaration for " + qname + "has fixed value constraints.");
897 string xsiType = reader.GetAttribute ("type", XmlSchema.InstanceNamespace);
898 if (xsiType != null) {
899 context.LocalTypeDefinition = GetLocalTypeDefinition (xsiType);
900 AssessLocalTypeDerivationOK (context.LocalTypeDefinition, element.ElementType, element.BlockResolved);
903 context.LocalTypeDefinition = null;
905 // 5 Not all things cannot be assessed here.
906 // It is common to 5.1 and 5.2
907 if (element.ElementType != null)
908 AssessStartElementLocallyValidType (SchemaType);
910 // 6. should be out from here.
911 // See invokation of AssessStartIdentityConstraints().
913 // 7 is going to be validated in Read() (in case of xmlreader's EOF).
916 // 3.3.4 Element Locally Valid (Type)
917 private void AssessStartElementLocallyValidType (object schemaType)
919 if (schemaType == null) { // 1.
920 HandleError ("Schema type does not exist.");
923 XmlSchemaComplexType cType = schemaType as XmlSchemaComplexType;
924 XmlSchemaSimpleType sType = schemaType as XmlSchemaSimpleType;
927 while (reader.MoveToNextAttribute ()) {
928 if (reader.NamespaceURI == XmlNamespaceManager.XmlnsXmlns)
930 if (reader.NamespaceURI != XmlSchema.InstanceNamespace)
931 HandleError ("Current simple type cannot accept attributes other than schema instance namespace.");
932 switch (reader.LocalName) {
935 case "schemaLocation":
936 case "noNamespaceSchemaLocation":
939 HandleError ("Unknown schema instance namespace attribute: " + reader.LocalName);
943 reader.MoveToElement ();
944 // 3.1.2 and 3.1.3 cannot be assessed here.
945 } else if (cType != null) {
946 if (cType.IsAbstract) { // 2.
947 HandleError ("Target complex type is abstract.");
951 AssessElementLocallyValidComplexType (cType);
955 // 3.4.4 Element Locally Valid (Complex Type)
956 private void AssessElementLocallyValidComplexType (XmlSchemaComplexType cType)
959 if (cType.IsAbstract)
960 HandleError ("Target complex type is abstract.");
962 // 2 (xsi:nil and content prohibition)
963 // See AssessStartElementSchemaValidity() and ValidateCharacters()
965 string elementNs = reader.NamespaceURI;
966 // 3. attribute uses and
968 while (reader.MoveToNextAttribute ()) {
969 if (reader.NamespaceURI == "http://www.w3.org/2000/xmlns/")
971 else if (reader.NamespaceURI == XmlSchema.InstanceNamespace)
973 XmlQualifiedName qname = new XmlQualifiedName (reader.LocalName, reader.NamespaceURI);
974 XmlSchemaObject attMatch = FindAttributeDeclaration (cType, qname, elementNs);
975 if (attMatch == null)
976 HandleError ("Attribute declaration was not found for " + qname);
978 XmlSchemaAttribute attdecl = attMatch as XmlSchemaAttribute;
979 if (attdecl == null) { // i.e. anyAttribute
980 // XmlSchemaAnyAttribute anyAttrMatch = attMatch as XmlSchemaAnyAttribute;
982 AssessAttributeLocallyValidUse (attdecl);
983 AssessAttributeLocallyValid (attdecl, true);
987 reader.MoveToElement ();
989 // Collect default attributes.
991 foreach (DictionaryEntry entry in cType.AttributeUses) {
992 XmlSchemaAttribute attr = (XmlSchemaAttribute) entry.Value;
993 if (reader [attr.QualifiedName.Name, attr.QualifiedName.Namespace] == null) {
994 if (attr.ValidatedUse == XmlSchemaUse.Required &&
995 attr.ValidatedFixedValue == null)
996 HandleError ("Required attribute " + attr.QualifiedName + " was not found.");
997 else if (attr.ValidatedDefaultValue != null || attr.ValidatedFixedValue != null)
998 defaultAttributesCache.Add (attr);
1001 defaultAttributes = (XmlSchemaAttribute [])
1002 defaultAttributesCache.ToArray (typeof (XmlSchemaAttribute));
1003 context.DefaultAttributes = defaultAttributes;
1004 defaultAttributesCache.Clear ();
1005 // 5. wild IDs was already checked above.
1008 // Spec 3.10.4 Item Valid (Wildcard)
1009 private static bool AttributeWildcardItemValid (XmlSchemaAnyAttribute anyAttr, XmlQualifiedName qname, string ns)
1011 if (anyAttr.HasValueAny)
1013 if (anyAttr.HasValueOther && (anyAttr.TargetNamespace == "" || ns != anyAttr.TargetNamespace))
1015 if (anyAttr.HasValueTargetNamespace && ns == anyAttr.TargetNamespace)
1017 if (anyAttr.HasValueLocal && ns == "")
1019 for (int i = 0; i < anyAttr.ResolvedNamespaces.Count; i++)
1020 if (anyAttr.ResolvedNamespaces [i] == ns)
1025 private XmlSchemaObject FindAttributeDeclaration (
1026 XmlSchemaComplexType cType,
1027 XmlQualifiedName qname,
1030 XmlSchemaObject result = cType.AttributeUses [qname];
1033 if (cType.AttributeWildcard == null)
1036 if (!AttributeWildcardItemValid (cType.AttributeWildcard, qname, reader.NamespaceURI))
1039 if (cType.AttributeWildcard.ResolvedProcessContents == XmlSchemaContentProcessing.Skip)
1040 return cType.AttributeWildcard;
1041 XmlSchemaAttribute attr = schemas.GlobalAttributes [qname] as XmlSchemaAttribute;
1044 if (cType.AttributeWildcard.ResolvedProcessContents == XmlSchemaContentProcessing.Lax)
1045 return cType.AttributeWildcard;
1050 // 3.2.4 Attribute Locally Valid and 3.4.4 - 5.wildIDs
1051 private void AssessAttributeLocallyValid (XmlSchemaAttribute attr, bool checkWildIDs)
1054 switch (reader.NamespaceURI) {
1055 case XmlNamespaceManager.XmlnsXml:
1056 case XmlNamespaceManager.XmlnsXmlns:
1057 case XmlSchema.InstanceNamespace:
1061 if (attr.AttributeType == null)
1062 HandleError ("Attribute type is missing for " + attr.QualifiedName);
1063 XmlSchemaDatatype dt = attr.AttributeType as XmlSchemaDatatype;
1065 dt = ((XmlSchemaSimpleType) attr.AttributeType).Datatype;
1066 // It is a bit heavy process, so let's omit as long as possible ;-)
1067 if (dt != XmlSchemaSimpleType.AnySimpleType || attr.ValidatedFixedValue != null) {
1068 string normalized = dt.Normalize (reader.Value);
1069 object parsedValue = null;
1071 parsedValue = dt.ParseValue (normalized, reader.NameTable, this.ParserContext.NamespaceManager);
1072 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
1073 HandleError ("Attribute value is invalid against its data type " + dt.TokenizedType, ex);
1075 if (attr.ValidatedFixedValue != null && attr.ValidatedFixedValue != normalized)
1076 HandleError ("The value of the attribute " + attr.QualifiedName + " does not match with its fixed value.");
1077 if (this.checkIdentity && checkWildIDs)
1078 AssessEachAttributeIdentityConstraint (dt, normalized, parsedValue);
1082 private void AssessEachAttributeIdentityConstraint (XmlSchemaDatatype dt,
1083 string normalized, object parsedValue)
1085 // Get normalized value and (if required) parsedValue if missing.
1086 switch (dt.TokenizedType) {
1087 case XmlTokenizedType.IDREFS:
1088 if (normalized == null)
1089 normalized = dt.Normalize (reader.Value);
1090 if (parsedValue == null)
1091 parsedValue = dt.ParseValue (normalized, reader.NameTable, ParserContext.NamespaceManager);
1093 case XmlTokenizedType.ID:
1094 case XmlTokenizedType.IDREF:
1095 if (normalized == null)
1096 normalized = dt.Normalize (reader.Value);
1100 // Validate identity constraints.
1101 switch (dt.TokenizedType) {
1102 case XmlTokenizedType.ID:
1103 if (thisElementId != null)
1104 HandleError ("ID type attribute was already assigned in the containing element.");
1105 thisElementId = normalized;
1106 if (idList.Contains (normalized))
1107 HandleError ("Duplicate ID value was found.");
1109 idList.Add (normalized, normalized);
1110 if (MissingIDReferences.Contains (normalized))
1111 MissingIDReferences.Remove (normalized);
1113 case XmlTokenizedType.IDREF:
1114 if (!idList.Contains (normalized))
1115 MissingIDReferences.Add (normalized);
1117 case XmlTokenizedType.IDREFS:
1118 string [] idrefs = (string []) parsedValue;
1119 for (int i = 0; i < idrefs.Length; i++) {
1120 string id = idrefs [i];
1121 if (!idList.Contains (id))
1122 MissingIDReferences.Add (id);
1128 private void AssessAttributeLocallyValidUse (XmlSchemaAttribute attr)
1130 // This is extra check than spec 3.5.4
1131 if (attr.ValidatedUse == XmlSchemaUse.Prohibited)
1132 HandleError ("Attribute " + attr.QualifiedName + " is prohibited in this context.");
1135 private void AssessEndElementSchemaValidity ()
1137 if (childParticleState == null)
1138 childParticleState = context.ParticleState;
1139 ValidateEndElementParticle (); // validate against childrens' state.
1141 if (shouldValidateCharacters) {
1142 ValidateEndCharacters ();
1143 shouldValidateCharacters = false;
1146 // 3.3.4 Assess ElementLocallyValidElement 5: value constraints.
1147 // 3.3.4 Assess ElementLocallyValidType 3.1.3. = StringValid(3.14.4)
1148 // => ValidateEndCharacters().
1150 // Reset Identity constraints.
1151 for (int i = 0; i < keyTables.Count; i++) {
1152 XsdKeyTable keyTable = this.keyTables [i] as XsdKeyTable;
1153 if (keyTable.StartDepth == reader.Depth) {
1154 EndIdentityValidation (keyTable);
1156 for (int k = 0; k < keyTable.Entries.Count; k++) {
1157 XsdKeyEntry entry = keyTable.Entries [k] as XsdKeyEntry;
1158 // Remove finished (maybe key not found) entries.
1159 if (entry.StartDepth == reader.Depth) {
1161 keyTable.FinishedEntries.Add (entry);
1162 else if (entry.KeySequence.SourceSchemaIdentity is XmlSchemaKey)
1163 HandleError ("Key sequence is missing.");
1164 keyTable.Entries.RemoveAt (k);
1167 // Pop validated key depth to find two or more fields.
1169 for (int j = 0; j < entry.KeyFields.Count; j++) {
1170 XsdKeyEntryField kf = entry.KeyFields [j];
1171 if (!kf.FieldFound && kf.FieldFoundDepth == reader.Depth) {
1172 kf.FieldFoundDepth = 0;
1173 kf.FieldFoundPath = null;
1180 for (int i = 0; i < keyTables.Count; i++) {
1181 XsdKeyTable keyseq = this.keyTables [i] as XsdKeyTable;
1182 if (keyseq.StartDepth == reader.Depth) {
1183 keyTables.RemoveAt (i);
1188 // Reset xsi:nil, if required.
1189 if (xsiNilDepth == reader.Depth)
1193 // 3.11.4 Identity Constraint Satisfied
1194 private void AssessStartIdentityConstraints ()
1196 if (tmpKeyrefPool != null)
1197 tmpKeyrefPool.Clear ();
1198 if (context.Element != null && context.Element.Constraints.Count > 0) {
1199 // (a) Create new key sequences, if required.
1200 for (int i = 0; i < context.Element.Constraints.Count; i++) {
1201 XmlSchemaIdentityConstraint ident = (XmlSchemaIdentityConstraint) context.Element.Constraints [i];
1202 XsdKeyTable seq = CreateNewKeyTable (ident);
1203 if (ident is XmlSchemaKeyref) {
1204 if (tmpKeyrefPool == null)
1205 tmpKeyrefPool = new ArrayList ();
1206 tmpKeyrefPool.Add (seq);
1211 // (b) Evaluate current key sequences.
1212 for (int i = 0; i < keyTables.Count; i++) {
1213 XsdKeyTable seq = (XsdKeyTable) keyTables [i];
1214 if (seq.SelectorMatches (this.elementQNameStack, reader) != null) {
1215 // creates and registers new entry.
1216 XsdKeyEntry entry = new XsdKeyEntry (seq, reader);
1217 seq.Entries.Add (entry);
1221 // (c) Evaluate field paths.
1222 for (int i = 0; i < keyTables.Count; i++) {
1223 XsdKeyTable seq = (XsdKeyTable) keyTables [i];
1224 // If possible, create new field entry candidates.
1225 for (int j = 0; j < seq.Entries.Count; j++) {
1226 XsdKeyEntry entry = seq.Entries [j] as XsdKeyEntry;
1228 entry.FieldMatches (this.elementQNameStack, this);
1229 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
1230 HandleError ("Identity field value is invalid against its data type.", ex);
1236 private XsdKeyTable CreateNewKeyTable (XmlSchemaIdentityConstraint ident)
1238 XsdKeyTable seq = new XsdKeyTable (ident, this);
1239 seq.StartDepth = reader.Depth;
1240 this.keyTables.Add (seq);
1244 private void EndIdentityValidation (XsdKeyTable seq)
1246 ArrayList errors = new ArrayList ();
1247 for (int i = 0; i < seq.Entries.Count; i++) {
1248 XsdKeyEntry entry = (XsdKeyEntry) seq.Entries [i];
1251 if (seq.SourceSchemaIdentity is XmlSchemaKey)
1252 errors.Add ("line " + entry.SelectorLineNumber + "position " + entry.SelectorLinePosition);
1254 if (errors.Count > 0)
1255 HandleError ("Invalid identity constraints were found. Key was not found. "
1256 + String.Join (", ", errors.ToArray (typeof (string)) as string []));
1259 // Find reference target
1260 XmlSchemaKeyref xsdKeyref = seq.SourceSchemaIdentity as XmlSchemaKeyref;
1261 if (xsdKeyref != null) {
1262 for (int i = this.keyTables.Count - 1; i >= 0; i--) {
1263 XsdKeyTable target = this.keyTables [i] as XsdKeyTable;
1264 if (target.SourceSchemaIdentity == xsdKeyref.Target) {
1265 seq.ReferencedKey = target;
1266 for (int j = 0; j < seq.FinishedEntries.Count; j++) {
1267 XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [j];
1268 for (int k = 0; k < target.FinishedEntries.Count; k++) {
1269 XsdKeyEntry targetEntry = (XsdKeyEntry) target.FinishedEntries [k];
1270 if (entry.CompareIdentity (targetEntry)) {
1271 entry.KeyRefFound = true;
1278 if (seq.ReferencedKey == null)
1279 HandleError ("Target key was not found.");
1280 for (int i = 0; i < seq.FinishedEntries.Count; i++) {
1281 XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [i];
1282 if (!entry.KeyRefFound)
1283 errors.Add (" line " + entry.SelectorLineNumber + ", position " + entry.SelectorLinePosition);
1285 if (errors.Count > 0)
1286 HandleError ("Invalid identity constraints were found. Referenced key was not found: "
1287 + String.Join (" / ", errors.ToArray (typeof (string)) as string []));
1291 // Overrided Methods
1293 public override void Close ()
1298 public override string GetAttribute (int i)
1300 switch (reader.NodeType) {
1301 case XmlNodeType.XmlDeclaration:
1302 case XmlNodeType.DocumentType:
1303 return reader.GetAttribute (i);
1306 if (reader.AttributeCount > i)
1307 reader.GetAttribute (i);
1308 int defIdx = i - reader.AttributeCount;
1309 if (i < AttributeCount)
1310 return defaultAttributes [defIdx].DefaultValue;
1312 throw new ArgumentOutOfRangeException ("i", i, "Specified attribute index is out of range.");
1315 public override string GetAttribute (string name)
1317 switch (reader.NodeType) {
1318 case XmlNodeType.XmlDeclaration:
1319 case XmlNodeType.DocumentType:
1320 return reader.GetAttribute (name);
1323 string value = reader.GetAttribute (name);
1327 XmlQualifiedName qname = SplitQName (name);
1328 return GetDefaultAttribute (qname.Name, qname.Namespace);
1331 private XmlQualifiedName SplitQName (string name)
1333 if (!XmlChar.IsName (name))
1334 throw new ArgumentException ("Invalid name was specified.", "name");
1336 Exception ex = null;
1337 XmlQualifiedName qname = XmlSchemaUtil.ToQName (reader, name, out ex);
1339 return XmlQualifiedName.Empty;
1344 public override string GetAttribute (string localName, string ns)
1346 switch (reader.NodeType) {
1347 case XmlNodeType.XmlDeclaration:
1348 case XmlNodeType.DocumentType:
1349 return reader.GetAttribute (localName, ns);
1352 string value = reader.GetAttribute (localName, ns);
1356 return GetDefaultAttribute (localName, ns);
1359 private string GetDefaultAttribute (string localName, string ns)
1361 int idx = this.FindDefaultAttribute (localName, ns);
1364 string value = defaultAttributes [idx].ValidatedDefaultValue;
1366 value = defaultAttributes [idx].ValidatedFixedValue;
1370 private int FindDefaultAttribute (string localName, string ns)
1372 for (int i = 0; i < this.defaultAttributes.Length; i++) {
1373 XmlSchemaAttribute attr = defaultAttributes [i];
1374 if (attr.QualifiedName.Name == localName &&
1375 (ns == null || attr.QualifiedName.Namespace == ns))
1381 bool IXmlLineInfo.HasLineInfo ()
1383 return readerLineInfo != null && readerLineInfo.HasLineInfo ();
1386 public override string LookupNamespace (string prefix)
1388 return reader.LookupNamespace (prefix);
1391 string IXmlNamespaceResolver.LookupNamespace (string prefix, bool atomizedNames)
1393 IXmlNamespaceResolver res = reader as IXmlNamespaceResolver;
1395 return res.LookupNamespace (prefix, atomizedNames);
1397 return reader.LookupNamespace (prefix);
1400 public override void MoveToAttribute (int i)
1402 switch (reader.NodeType) {
1403 case XmlNodeType.XmlDeclaration:
1404 case XmlNodeType.DocumentType:
1405 reader.MoveToAttribute (i);
1409 currentQName = null;
1410 if (i < reader.AttributeCount) {
1411 reader.MoveToAttribute (i);
1412 this.currentDefaultAttribute = -1;
1413 this.defaultAttributeConsumed = false;
1416 if (i < AttributeCount) {
1417 this.currentDefaultAttribute = i - reader.AttributeCount;
1418 this.defaultAttributeConsumed = false;
1421 throw new ArgumentOutOfRangeException ("i", i, "Attribute index is out of range.");
1424 public override bool MoveToAttribute (string name)
1426 switch (reader.NodeType) {
1427 case XmlNodeType.XmlDeclaration:
1428 case XmlNodeType.DocumentType:
1429 return reader.MoveToAttribute (name);
1432 currentQName = null;
1433 bool b = reader.MoveToAttribute (name);
1435 this.currentDefaultAttribute = -1;
1436 this.defaultAttributeConsumed = false;
1440 return MoveToDefaultAttribute (name, null);
1443 public override bool MoveToAttribute (string localName, string ns)
1445 switch (reader.NodeType) {
1446 case XmlNodeType.XmlDeclaration:
1447 case XmlNodeType.DocumentType:
1448 return reader.MoveToAttribute (localName, ns);
1451 currentQName = null;
1452 bool b = reader.MoveToAttribute (localName, ns);
1454 this.currentDefaultAttribute = -1;
1455 this.defaultAttributeConsumed = false;
1459 return MoveToDefaultAttribute (localName, ns);
1462 private bool MoveToDefaultAttribute (string localName, string ns)
1464 int idx = this.FindDefaultAttribute (localName, ns);
1467 currentDefaultAttribute = idx;
1468 defaultAttributeConsumed = false;
1472 public override bool MoveToElement ()
1474 currentDefaultAttribute = -1;
1475 defaultAttributeConsumed = false;
1476 currentQName = null;
1477 return reader.MoveToElement ();
1480 public override bool MoveToFirstAttribute ()
1482 switch (reader.NodeType) {
1483 case XmlNodeType.XmlDeclaration:
1484 case XmlNodeType.DocumentType:
1485 return reader.MoveToFirstAttribute ();
1488 currentQName = null;
1489 if (reader.AttributeCount > 0) {
1490 bool b = reader.MoveToFirstAttribute ();
1492 currentDefaultAttribute = -1;
1493 defaultAttributeConsumed = false;
1498 if (this.defaultAttributes.Length > 0) {
1499 currentDefaultAttribute = 0;
1500 defaultAttributeConsumed = false;
1507 public override bool MoveToNextAttribute ()
1509 switch (reader.NodeType) {
1510 case XmlNodeType.XmlDeclaration:
1511 case XmlNodeType.DocumentType:
1512 return reader.MoveToNextAttribute ();
1515 currentQName = null;
1516 if (currentDefaultAttribute >= 0) {
1517 if (defaultAttributes.Length == currentDefaultAttribute + 1)
1519 currentDefaultAttribute++;
1520 defaultAttributeConsumed = false;
1524 bool b = reader.MoveToNextAttribute ();
1526 currentDefaultAttribute = -1;
1527 defaultAttributeConsumed = false;
1531 if (defaultAttributes.Length > 0) {
1532 currentDefaultAttribute = 0;
1533 defaultAttributeConsumed = false;
1540 private void ExamineAdditionalSchema ()
1542 XmlSchema schema = null;
1543 string schemaLocation = reader.GetAttribute ("schemaLocation", XmlSchema.InstanceNamespace);
1544 bool schemaAdded = false;
1545 if (schemaLocation != null) {
1546 string [] tmp = null;
1548 schemaLocation = XmlSchemaDatatype.FromName ("token", XmlSchema.Namespace).Normalize (schemaLocation);
1549 tmp = schemaLocation.Split (XmlChar.WhitespaceChars);
1550 } catch (Exception ex) {
1551 HandleError ("Invalid schemaLocation attribute format.", ex, true);
1552 tmp = new string [0];
1554 if (tmp.Length % 2 != 0)
1555 HandleError ("Invalid schemaLocation attribute format.");
1556 for (int i = 0; i < tmp.Length; i += 2) {
1558 XmlTextReader xtr = null;
1560 absUri = new Uri ((this.BaseURI != "" ? new Uri (BaseURI) : null), tmp [i + 1]);
1561 xtr = new XmlTextReader (absUri.ToString (), NameTable);
1562 schema = XmlSchema.Read (xtr, null);
1563 } catch (Exception) { // FIXME: (wishlist) It is bad manner ;-(
1564 HandleError ("Could not resolve schema location URI: " + absUri, null, true);
1570 if (schema.TargetNamespace == null)
1571 schema.TargetNamespace = tmp [i];
1572 else if (schema.TargetNamespace != tmp [i])
1573 HandleError ("Specified schema has different target namespace.");
1576 if (schema != null) {
1577 if (!schemas.Contains (schema.TargetNamespace)) {
1579 schemas.Add (schema);
1583 string noNsSchemaLocation = reader.GetAttribute ("noNamespaceSchemaLocation", XmlSchema.InstanceNamespace);
1584 if (noNsSchemaLocation != null) {
1586 XmlTextReader xtr = null;
1588 absUri = new Uri ((this.BaseURI != "" ? new Uri (BaseURI) : null), noNsSchemaLocation);
1589 xtr = new XmlTextReader (absUri.ToString (), NameTable);
1590 schema = XmlSchema.Read (xtr, null);
1591 } catch (Exception) { // FIXME: (wishlist) It is bad manner ;-(
1592 HandleError ("Could not resolve schema location URI: " + absUri, null, true);
1597 if (schema != null && schema.TargetNamespace != null)
1598 HandleError ("Specified schema has different target namespace.");
1600 if (schema != null) {
1601 if (!schemas.Contains (schema.TargetNamespace)) {
1603 schemas.Add (schema);
1606 // FIXME: should call Reprocess()?
1611 private bool HasMissingIDReferences ()
1613 return missingIDReferences != null
1614 && missingIDReferences.Count > 0;
1617 public override bool Read ()
1619 currentDefaultAttribute = -1;
1620 defaultAttributeConsumed = false;
1621 currentQName = null;
1622 if (this.checkIdentity)
1623 thisElementId = null;
1624 defaultAttributes = new XmlSchemaAttribute [0];
1625 if (!schemas.IsCompiled)
1628 elementQNameStack.RemoveAt (elementQNameStack.Count - 1);
1632 bool result = reader.Read ();
1633 // 3.3.4 ElementLocallyValidElement 7 = Root Valid.
1634 if (!result && this.checkIdentity &&
1635 HasMissingIDReferences ())
1636 HandleError ("There are missing ID references: " +
1638 this.missingIDReferences.ToArray (typeof (string)) as string []));
1640 switch (reader.NodeType) {
1641 case XmlNodeType.Element:
1642 // FIXME: schemaLocation could be specified
1644 if (reader.Depth == 0)
1645 ExamineAdditionalSchema ();
1647 this.elementQNameStack.Add (new XmlQualifiedName (reader.LocalName, reader.NamespaceURI));
1649 // If there is no schema information, then no validation is performed.
1650 if (schemas.Count == 0)
1653 if (skipValidationDepth < 0 || reader.Depth <= skipValidationDepth) {
1654 if (shouldValidateCharacters) {
1655 ValidateEndCharacters ();
1656 shouldValidateCharacters = false;
1658 AssessStartElementSchemaValidity ();
1659 storedCharacters.Length = 0;
1664 if (reader.IsEmptyElement)
1665 goto case XmlNodeType.EndElement;
1667 shouldValidateCharacters = true;
1669 case XmlNodeType.EndElement:
1670 if (reader.Depth == skipValidationDepth) {
1671 skipValidationDepth = -1;
1675 AssessEndElementSchemaValidity ();
1677 storedCharacters.Length = 0;
1678 childParticleState = null;
1682 case XmlNodeType.CDATA:
1683 case XmlNodeType.SignificantWhitespace:
1684 case XmlNodeType.Text:
1685 XmlSchemaComplexType ct = context.ActualType as XmlSchemaComplexType;
1686 if (ct != null && storedCharacters.Length > 0) {
1687 switch (ct.ContentType) {
1688 case XmlSchemaContentType.ElementOnly:
1689 case XmlSchemaContentType.Empty:
1690 HandleError ("Not allowed character content was found.");
1695 ValidateCharacters ();
1702 public override bool ReadAttributeValue ()
1704 if (currentDefaultAttribute < 0)
1705 return reader.ReadAttributeValue ();
1707 if (this.defaultAttributeConsumed)
1710 defaultAttributeConsumed = true;
1715 public override string ReadInnerXml ()
1717 // MS.NET 1.0 has a serious bug here. It skips validation.
1718 return reader.ReadInnerXml ();
1721 public override string ReadOuterXml ()
1723 // MS.NET 1.0 has a serious bug here. It skips validation.
1724 return reader.ReadOuterXml ();
1728 // XmlReader.ReadString() should call derived this.Read().
1729 public override string ReadString ()
1732 return reader.ReadString ();
1734 return base.ReadString ();
1738 // This class itself does not have this feature.
1739 public override void ResolveEntity ()
1741 reader.ResolveEntity ();
1744 internal class XsdValidationContext
1746 Hashtable contextStack;
1748 public XsdValidationContext ()
1750 contextStack = new Hashtable ();
1753 // Some of them might be missing (See the spec section 5.3, and also 3.3.4).
1754 public XmlSchemaElement Element;
1755 public XsdValidationState ParticleState;
1756 public XmlSchemaAttribute [] DefaultAttributes;
1758 // Some of them might be missing (See the spec section 5.3).
1759 public object SchemaType;
1761 public object LocalTypeDefinition;
1763 public object ActualType {
1765 if (LocalTypeDefinition != null)
1766 return LocalTypeDefinition;
1772 public void Clear ()
1776 ParticleState = null;
1777 LocalTypeDefinition = null;
1780 public void PushScope (int depth)
1782 contextStack [depth] = this.MemberwiseClone ();
1785 public void PopScope (int depth)
1788 contextStack.Remove (depth + 1);
1791 public void Load (int depth)
1794 XsdValidationContext restored = (XsdValidationContext) contextStack [depth];
1795 if (restored != null) {
1796 this.Element = restored.Element;
1797 this.ParticleState = restored.ParticleState;
1798 this.SchemaType = restored.SchemaType;
1799 this.LocalTypeDefinition = restored.LocalTypeDefinition;