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.
15 using System.Collections;
16 using System.Collections.Specialized;
19 using System.Xml.Schema;
22 namespace Mono.Xml.Schema
24 public class XsdValidatingReader : XmlReader, IXmlLineInfo, IHasXmlSchemaInfo, IHasXmlParserContext
26 static char [] wsChars = new char [] {' ', '\t', '\n', '\r'};
29 XmlValidatingReader xvReader;
31 IHasXmlSchemaInfo sourceReaderSchemaInfo;
32 IXmlLineInfo readerLineInfo;
33 bool laxElementValidation = true;
34 bool reportNoValidationError;
35 XmlSchemaCollection schemas = new XmlSchemaCollection ();
36 bool namespaces = true;
38 Hashtable idList = new Hashtable ();
39 ArrayList missingIDReferences = new ArrayList ();
42 ArrayList keyTables = new ArrayList ();
43 ArrayList currentKeyFieldConsumers = new ArrayList ();
45 XsdValidationStateManager stateManager = new XsdValidationStateManager ();
46 XsdValidationContext context = new XsdValidationContext ();
47 XsdValidationState childParticleState;
50 StringBuilder storedCharacters = new StringBuilder ();
51 bool shouldValidateCharacters;
52 int skipValidationDepth = -1;
54 XmlSchemaAttribute [] defaultAttributes = new XmlSchemaAttribute [0];
55 int currentDefaultAttribute = -1;
56 XmlQualifiedName currentQName;
58 ArrayList elementQNameStack = new ArrayList ();
62 int nonDefaultAttributeCount;
63 bool defaultAttributeConsumed;
65 // Validation engine cached object
66 ArrayList defaultAttributesCache = new ArrayList ();
67 ArrayList tmpKeyrefPool = new ArrayList ();
70 public XsdValidatingReader (XmlReader reader)
75 public XsdValidatingReader (XmlReader reader, XmlReader validatingReader)
78 xvReader = validatingReader as XmlValidatingReader;
79 if (xvReader != null) {
80 if (xvReader.ValidationType == ValidationType.None)
81 reportNoValidationError = true;
83 readerLineInfo = reader as IXmlLineInfo;
84 sourceReaderSchemaInfo = reader as IHasXmlSchemaInfo;
88 private XmlQualifiedName CurrentQName {
90 if (currentQName == null)
91 currentQName = new XmlQualifiedName (LocalName, NamespaceURI);
96 internal ArrayList CurrentKeyFieldConsumers {
97 get { return currentKeyFieldConsumers; }
100 // Public Non-overrides
102 public int XsiNilDepth {
103 get { return xsiNilDepth; }
106 public bool Namespaces {
107 get { return namespaces; }
108 set { namespaces = value; }
111 public XmlReader Reader {
112 get { return reader; }
115 // This is required to resolve xsi:schemaLocation
116 public XmlResolver XmlResolver {
122 // This should be changed before the first Read() call.
123 public XmlSchemaCollection Schemas {
124 get { return schemas; }
127 public object SchemaType {
129 if (ReadState != ReadState.Interactive)
133 case XmlNodeType.Element:
134 if (context.ActualType != null)
135 return context.ActualType;
136 else if (context.Element != null)
137 return context.Element.ElementType;
139 return SourceReaderSchemaType;
140 case XmlNodeType.Attribute:
141 XmlSchemaComplexType ct = context.ActualType as XmlSchemaComplexType;
143 XmlSchemaAttribute attdef = ct.AttributeUses [CurrentQName] as XmlSchemaAttribute;
145 return attdef.AttributeType;
147 return SourceReaderSchemaType;
149 return SourceReaderSchemaType;
154 private object SourceReaderSchemaType {
155 get { return this.sourceReaderSchemaInfo != null ? sourceReaderSchemaInfo.SchemaType : null; }
158 // This property is never used in Mono.
159 public ValidationType ValidationType {
161 if (reportNoValidationError)
162 return ValidationType.None;
164 return ValidationType.Schema;
168 // It is used only for independent XmlReader use, not for XmlValidatingReader.
169 public object ReadTypedValue ()
171 XmlSchemaDatatype dt = SchemaType as XmlSchemaDatatype;
172 XmlSchemaSimpleType st = SchemaType as XmlSchemaSimpleType;
179 case XmlNodeType.Element:
183 storedCharacters.Length = 0;
188 case XmlNodeType.SignificantWhitespace:
189 case XmlNodeType.Text:
190 case XmlNodeType.CDATA:
191 storedCharacters.Append (Value);
193 case XmlNodeType.Comment:
199 } while (loop && !EOF);
200 return dt.ParseValue (storedCharacters.ToString (), NameTable, ParserContext.NamespaceManager);
201 case XmlNodeType.Attribute:
202 return dt.ParseValue (Value, NameTable, ParserContext.NamespaceManager);
208 public ValueType ReadTypedValueType ()
210 XmlSchemaDatatype dt = SchemaType as XmlSchemaDatatype;
211 XmlSchemaSimpleType st = SchemaType as XmlSchemaSimpleType;
218 case XmlNodeType.Element:
222 storedCharacters.Length = 0;
227 case XmlNodeType.SignificantWhitespace:
228 case XmlNodeType.Text:
229 case XmlNodeType.CDATA:
230 storedCharacters.Append (Value);
232 case XmlNodeType.Comment:
238 } while (loop && !EOF);
239 return dt.ParseValueType (storedCharacters.ToString (), NameTable, ParserContext.NamespaceManager);
240 case XmlNodeType.Attribute:
241 return dt.ParseValueType (Value, NameTable, ParserContext.NamespaceManager);
247 public ValidationEventHandler ValidationEventHandler;
249 // Public Overrided Properties
251 public override int AttributeCount {
254 if (NodeType == XmlNodeType.Element)
255 return attributeCount;
259 return reader.AttributeCount;
261 return nonDefaultAttributeCount + defaultAttributes.Length;
265 public override string BaseURI {
266 get { return reader.BaseURI; }
269 // If this class is used to implement XmlValidatingReader,
270 // it should be left to DTDValidatingReader. In other cases,
271 // it depends on the reader's ability.
272 public override bool CanResolveEntity {
273 get { return reader.CanResolveEntity; }
276 public override int Depth {
278 if (currentDefaultAttribute < 0)
280 if (this.defaultAttributeConsumed)
281 return reader.Depth + 2;
282 return reader.Depth + 1;
286 public override bool EOF {
287 get { return reader.EOF; }
290 public override bool HasValue {
292 if (currentDefaultAttribute < 0)
293 return reader.HasValue;
298 public override bool IsDefault {
300 if (currentDefaultAttribute < 0)
301 return reader.IsDefault;
306 public override bool IsEmptyElement {
308 if (currentDefaultAttribute < 0)
309 return reader.IsEmptyElement;
314 public override string this [int i] {
315 get { return GetAttribute (i); }
318 public override string this [string name] {
319 get { return GetAttribute (name); }
322 public override string this [string localName, string ns] {
323 get { return GetAttribute (localName, ns); }
326 int IXmlLineInfo.LineNumber {
327 get { return readerLineInfo != null ? readerLineInfo.LineNumber : 0; }
330 int IXmlLineInfo.LinePosition {
331 get { return readerLineInfo != null ? readerLineInfo.LinePosition : 0; }
334 public override string LocalName {
336 if (currentDefaultAttribute < 0)
337 return reader.LocalName;
338 if (defaultAttributeConsumed)
340 return defaultAttributes [currentDefaultAttribute].QualifiedName.Name;
344 public override string Name {
346 if (currentDefaultAttribute < 0)
348 if (defaultAttributeConsumed)
351 XmlQualifiedName qname = defaultAttributes [currentDefaultAttribute].QualifiedName;
352 string prefix = Prefix;
353 if (prefix == String.Empty)
356 return String.Concat (prefix, ":", qname.Name);
360 public override string NamespaceURI {
362 if (currentDefaultAttribute < 0)
363 return reader.NamespaceURI;
364 if (defaultAttributeConsumed)
366 return defaultAttributes [currentDefaultAttribute].QualifiedName.Namespace;
370 public override XmlNameTable NameTable {
371 get { return reader.NameTable; }
374 public override XmlNodeType NodeType {
376 if (currentDefaultAttribute < 0)
377 return reader.NodeType;
378 if (defaultAttributeConsumed)
379 return XmlNodeType.Text;
380 return XmlNodeType.Attribute;
384 public XmlParserContext ParserContext {
385 get { return XmlSchemaUtil.GetParserContext (reader); }
388 public override string Prefix {
390 if (currentDefaultAttribute < 0)
391 return reader.Prefix;
392 if (defaultAttributeConsumed)
394 XmlQualifiedName qname = defaultAttributes [currentDefaultAttribute].QualifiedName;
395 string prefix = this.ParserContext.NamespaceManager.LookupPrefix (qname.Namespace);
403 public override char QuoteChar {
404 get { return reader.QuoteChar; }
407 public override ReadState ReadState {
408 get { return reader.ReadState; }
411 public override string Value {
413 if (currentDefaultAttribute < 0)
415 string value = defaultAttributes [currentDefaultAttribute].ValidatedDefaultValue;
417 value = defaultAttributes [currentDefaultAttribute].ValidatedFixedValue;
422 XmlQualifiedName qnameXmlLang = new XmlQualifiedName ("lang", XmlNamespaceManager.XmlnsXml);
424 public override string XmlLang {
426 string xmlLang = reader.XmlLang;
429 int idx = this.FindDefaultAttribute ("lang", XmlNamespaceManager.XmlnsXml);
432 xmlLang = defaultAttributes [idx].ValidatedDefaultValue;
434 xmlLang = defaultAttributes [idx].ValidatedFixedValue;
439 public override XmlSpace XmlSpace {
441 XmlSpace space = reader.XmlSpace;
442 if (space != XmlSpace.None)
444 int idx = this.FindDefaultAttribute ("space", XmlNamespaceManager.XmlnsXml);
446 return XmlSpace.None;
447 string spaceSpec = defaultAttributes [idx].ValidatedDefaultValue;
448 if (spaceSpec == null)
449 spaceSpec = defaultAttributes [idx].ValidatedFixedValue;
450 return (XmlSpace) Enum.Parse (typeof (XmlSpace), spaceSpec, false);
456 private XmlQualifiedName QualifyName (string name)
458 int colonAt = name.IndexOf (':');
460 return new XmlQualifiedName (name, null);
462 return new XmlQualifiedName (name.Substring (colonAt + 1),
463 LookupNamespace (name.Substring (0, colonAt)));
466 private void HandleError (string error)
468 HandleError (error, null);
471 private void HandleError (string error, Exception innerException)
473 HandleError (error, innerException, false);
476 private void HandleError (string error, Exception innerException, bool isWarning)
478 if (reportNoValidationError) // extra quick check
481 XmlSchemaException schemaException = new XmlSchemaException (error,
482 this, this.BaseURI, null, innerException);
483 HandleError (schemaException, isWarning);
486 private void HandleError (XmlSchemaException schemaException)
488 HandleError (schemaException, false);
491 private void HandleError (XmlSchemaException schemaException, bool isWarning)
493 if (reportNoValidationError)
496 ValidationEventArgs e = new ValidationEventArgs (schemaException,
497 schemaException.Message, isWarning ? XmlSeverityType.Warning : XmlSeverityType.Error);
499 if (this.ValidationEventHandler != null)
500 this.ValidationEventHandler (this, e);
501 else if (xvReader != null)
502 xvReader.OnValidationEvent (this, e);
503 else if (e.Severity == XmlSeverityType.Error)
505 this.xvReader.OnValidationEvent (this, e);
511 private XmlSchemaElement FindElement (string name, string ns)
513 foreach (XmlSchema target in schemas) {
514 XmlSchema matches = target.Schemas [ns];
515 if (matches != null) {
516 XmlSchemaElement result = target.Elements [new XmlQualifiedName (name, ns)] as XmlSchemaElement;
524 private XmlSchemaType FindType (XmlQualifiedName qname)
526 foreach (XmlSchema target in schemas) {
527 XmlSchemaType type = target.SchemaTypes [qname] as XmlSchemaType;
534 private void ValidateStartElementParticle ()
536 stateManager.CurrentElement = null;
537 context.ParticleState = context.ParticleState.EvaluateStartElement (reader.LocalName, reader.NamespaceURI);
538 if (context.ParticleState == XsdValidationState.Invalid)
539 HandleError ("Invalid start element: " + reader.NamespaceURI + ":" + reader.LocalName);
541 context.Element = stateManager.CurrentElement;
542 if (context.Element != null)
543 context.SchemaType = context.Element.ElementType;
546 private void ValidateEndElementParticle ()
548 if (childParticleState != null) {
549 if (!childParticleState.EvaluateEndElement ()) {
550 HandleError ("Invalid end element: " + reader.Name);
553 context.PopScope (reader.Depth);
556 // Utility for missing validation completion related to child items.
557 private void ValidateCharacters ()
559 // TODO: value context validation here.
560 if (xsiNilDepth >= 0 && xsiNilDepth < reader.Depth)
561 HandleError ("Element item appeared, while current element context is nil.");
563 storedCharacters.Append (reader.Value);
566 // Utility for missing validation completion related to child items.
567 private void ValidateEndCharacters ()
569 if (context.ActualType == null)
572 string value = storedCharacters.ToString ();
574 if (storedCharacters.Length == 0) {
575 // 3.3.4 Element Locally Valid (Element) 5.1.2
576 // TODO: check entire DefaultValid (3.3.6)
577 if (context.Element != null) {
578 if (context.Element.ValidatedDefaultValue != null)
579 value = context.Element.ValidatedDefaultValue;
583 XmlSchemaDatatype dt = context.ActualType as XmlSchemaDatatype;
584 XmlSchemaSimpleType st = context.ActualType as XmlSchemaSimpleType;
589 XmlSchemaComplexType ct = context.ActualType as XmlSchemaComplexType;
591 switch (ct.ContentType) {
592 case XmlSchemaContentType.ElementOnly:
593 case XmlSchemaContentType.Empty:
594 if (storedCharacters.Length > 0)
595 HandleError ("Character content not allowed.");
601 // 3.3.4 Element Locally Valid (Element) :: 5.2.2.2. Fixed value constraints
602 if (context.Element != null && context.Element.ValidatedFixedValue != null)
603 if (value != context.Element.ValidatedFixedValue)
604 HandleError ("Fixed value constraint was not satisfied.");
605 AssessStringValid (st, dt, value);
608 // Identity field value
609 while (this.currentKeyFieldConsumers.Count > 0) {
610 XsdKeyEntryField field = this.currentKeyFieldConsumers [0] as XsdKeyEntryField;
611 if (field.Identity != null)
612 HandleError ("Two or more identical field was found. Former value is '" + field.Identity + "' .");
613 object identity = null; // This means empty value
616 identity = dt.ParseValue (value, NameTable, ParserContext.NamespaceManager);
617 } catch (Exception ex) { // FIXME: (wishlist) This is bad manner ;-(
618 HandleError ("Identity value is invalid against its data type " + dt.TokenizedType, ex);
621 if (identity == null)
624 if (!field.SetIdentityField (identity, reader.Depth == xsiNilDepth, dt as XsdAnySimpleType, this))
625 HandleError ("Two or more identical key value was found: '" + value + "' .");
626 this.currentKeyFieldConsumers.RemoveAt (0);
629 shouldValidateCharacters = false;
632 // 3.14.4 String Valid
633 private void AssessStringValid (XmlSchemaSimpleType st,
634 XmlSchemaDatatype dt, string value)
636 XmlSchemaDatatype validatedDatatype = dt;
638 string normalized = validatedDatatype.Normalize (value);
640 XmlSchemaDatatype itemDatatype;
641 XmlSchemaSimpleType itemSimpleType;
642 switch (st.DerivedBy) {
643 case XmlSchemaDerivationMethod.List:
644 XmlSchemaSimpleTypeList listContent = st.Content as XmlSchemaSimpleTypeList;
645 values = normalized.Split (wsChars);
646 itemDatatype = listContent.ValidatedListItemType as XmlSchemaDatatype;
647 itemSimpleType = listContent.ValidatedListItemType as XmlSchemaSimpleType;
648 foreach (string each in values) {
649 if (each == String.Empty)
651 // validate against ValidatedItemType
652 if (itemDatatype != null) {
654 itemDatatype.ParseValue (each, NameTable, ParserContext.NamespaceManager);
655 } catch (Exception ex) { // FIXME: (wishlist) better exception handling ;-(
656 HandleError ("List type value contains one or more invalid values.", ex);
661 AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
664 case XmlSchemaDerivationMethod.Union:
665 XmlSchemaSimpleTypeUnion union = st.Content as XmlSchemaSimpleTypeUnion;
667 string each = normalized;
668 // validate against ValidatedItemType
670 foreach (object eachType in union.ValidatedTypes) {
671 itemDatatype = eachType as XmlSchemaDatatype;
672 itemSimpleType = eachType as XmlSchemaSimpleType;
673 if (itemDatatype != null) {
675 itemDatatype.ParseValue (each, NameTable, ParserContext.NamespaceManager);
676 } catch (Exception) { // FIXME: (wishlist) better exception handling ;-(
682 AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
683 } catch (XmlSchemaException) {
691 HandleError ("Union type value contains one or more invalid values.");
696 case XmlSchemaDerivationMethod.Restriction:
697 XmlSchemaSimpleTypeRestriction str = st.Content as XmlSchemaSimpleTypeRestriction;
700 /* Don't forget to validate against inherited type's facets
701 * Could we simplify this by assuming that the basetype will also
704 // mmm, will check later.
705 XmlSchemaSimpleType baseType = st.BaseXmlSchemaType as XmlSchemaSimpleType;
706 if (baseType != null) {
707 AssessStringValid(baseType, dt, normalized);
709 if (!str.ValidateValueWithFacets (normalized, NameTable)) {
710 HandleError ("Specified value was invalid against the facets.");
714 validatedDatatype = st.Datatype;
718 if (validatedDatatype != null) {
720 validatedDatatype.ParseValue (value, NameTable, ParserContext.NamespaceManager);
721 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
722 HandleError ("Invalidly typed data was specified.", ex);
727 private object GetLocalTypeDefinition (string name)
729 object xsiType = null;
730 XmlQualifiedName typeQName = QualifyName (name);
731 if (typeQName == XmlSchemaComplexType.AnyTypeName)
732 xsiType = XmlSchemaComplexType.AnyType;
733 else if (XmlSchemaUtil.IsBuiltInDatatypeName (typeQName))
734 xsiType = XmlSchemaDatatype.FromName (typeQName);
736 xsiType = FindType (typeQName);
740 // It is common to ElementLocallyValid::4 and SchemaValidityAssessment::1.2.1.2.4
741 private void AssessLocalTypeDerivationOK (object xsiType, object baseType, XmlSchemaDerivationMethod flag)
743 XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
744 XmlSchemaComplexType baseComplexType = baseType as XmlSchemaComplexType;
745 XmlSchemaComplexType xsiComplexType = xsiSchemaType as XmlSchemaComplexType;
746 if (xsiType != baseType) {
747 // Extracted (not extraneous) check for 3.4.6 TypeDerivationOK.
748 if (baseComplexType != null)
749 flag |= baseComplexType.BlockResolved;
750 if (flag == XmlSchemaDerivationMethod.All) {
751 HandleError ("Prohibited element type substitution.");
753 } else if (xsiSchemaType != null && (flag & xsiSchemaType.DerivedBy) != 0) {
754 HandleError ("Prohibited element type substitution.");
759 if (xsiComplexType != null)
761 xsiComplexType.ValidateTypeDerivationOK (baseType, null, null);
762 } catch (XmlSchemaException ex) {
763 // HandleError ("Locally specified schema complex type derivation failed. " + ex.Message, ex);
767 XmlSchemaSimpleType xsiSimpleType = xsiType as XmlSchemaSimpleType;
768 if (xsiSimpleType != null) {
770 xsiSimpleType.ValidateTypeDerivationOK (baseType, null, null, true);
771 } catch (XmlSchemaException ex) {
772 // HandleError ("Locally specified schema simple type derivation failed. " + ex.Message, ex);
776 else if (xsiType is XmlSchemaDatatype) {
780 HandleError ("Primitive data type cannot be derived type using xsi:type specification.");
784 // Section 3.3.4 of the spec.
785 private void AssessStartElementSchemaValidity ()
787 // If the reader is inside xsi:nil (and failed on validation),
788 // then simply skip its content.
789 if (xsiNilDepth >= 0 && xsiNilDepth < reader.Depth)
790 HandleError ("Element item appeared, while current element context is nil.");
792 context.Load (reader.Depth);
793 if (childParticleState != null) {
794 context.ParticleState = childParticleState;
795 childParticleState = null;
798 // If validation state exists, then first assess particle validity.
799 context.SchemaType = null;
800 if (context.ParticleState != null) {
801 ValidateStartElementParticle ();
804 string xsiNilValue = reader.GetAttribute ("nil", XmlSchema.InstanceNamespace);
805 if (xsiNilValue != null)
806 xsiNilValue = xsiNilValue.Trim (XmlChar.WhitespaceChars);
807 bool isXsiNil = xsiNilValue == "true";
808 if (isXsiNil && this.xsiNilDepth < 0)
809 xsiNilDepth = reader.Depth;
811 // [Schema Validity Assessment (Element) 1.2]
812 // Evaluate "local type definition" from xsi:type.
813 // (See spec 3.3.4 Schema Validity Assessment (Element) 1.2.1.2.3.
814 // Note that Schema Validity Assessment(Element) 1.2 takes
815 // precedence than 1.1 of that.
817 string xsiTypeName = reader.GetAttribute ("type", XmlSchema.InstanceNamespace);
818 if (xsiTypeName != null) {
819 xsiTypeName = xsiTypeName.Trim (XmlChar.WhitespaceChars);
820 object xsiType = GetLocalTypeDefinition (xsiTypeName);
822 HandleError ("The instance type was not found: " + xsiTypeName + " .");
824 XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
825 if (xsiSchemaType != null && this.context.Element != null) {
826 XmlSchemaType elemBaseType = context.Element.ElementType as XmlSchemaType;
827 if (elemBaseType != null && (xsiSchemaType.DerivedBy & elemBaseType.FinalResolved) != 0)
828 HandleError ("The instance type is prohibited by the type of the context element.");
829 if (elemBaseType != xsiType && (xsiSchemaType.DerivedBy & this.context.Element.BlockResolved) != 0)
830 HandleError ("The instance type is prohibited by the context element.");
832 XmlSchemaComplexType xsiComplexType = xsiType as XmlSchemaComplexType;
833 if (xsiComplexType != null && xsiComplexType.IsAbstract)
834 HandleError ("The instance type is abstract: " + xsiTypeName + " .");
836 // If current schema type exists, then this xsi:type must be
837 // valid extension of that type. See 1.2.1.2.4.
838 if (context.Element != null) {
839 // FIXME: supply *correct* base type
840 AssessLocalTypeDerivationOK (xsiType, context.Element.ElementType, context.Element.BlockResolved);
842 AssessStartElementLocallyValidType (xsiType); // 1.2.2:
843 context.LocalTypeDefinition = xsiType;
848 context.LocalTypeDefinition = null;
850 // Create Validation Root, if not exist.
851 // [Schema Validity Assessment (Element) 1.1]
852 if (context.Element == null)
853 context.Element = FindElement (reader.LocalName, reader.NamespaceURI);
854 if (context.Element != null) {
855 if (xsiTypeName == null) {
856 context.SchemaType = context.Element.ElementType;
857 AssessElementLocallyValidElement (context.Element, xsiNilValue); // 1.1.2
861 switch (stateManager.ProcessContents) {
862 case XmlSchemaContentProcessing.Skip:
864 case XmlSchemaContentProcessing.Lax:
866 schema = schemas [reader.NamespaceURI];
867 if (schema != null && !schema.missedSubComponents)
868 HandleError ("Element declaration for " + reader.LocalName + " is missing.");
872 schema = schemas [reader.NamespaceURI];
873 if (xsiTypeName == null && (schema == null || !schema.missedSubComponents))
874 HandleError ("Element declaration for " + reader.LocalName + " is missing.");
879 if (stateManager.ProcessContents == XmlSchemaContentProcessing.Skip)
880 skipValidationDepth = reader.Depth;
882 // Finally, create child particle state.
883 XmlSchemaComplexType xsComplexType = SchemaType as XmlSchemaComplexType;
884 if (xsComplexType != null)
885 childParticleState = stateManager.Create (xsComplexType.ValidatableParticle);
886 else if (stateManager.ProcessContents == XmlSchemaContentProcessing.Lax)
887 childParticleState = stateManager.Create (XmlSchemaAny.AnyTypeContent);
889 childParticleState = stateManager.Create (XmlSchemaParticle.Empty);
891 AssessStartIdentityConstraints ();
893 context.PushScope (reader.Depth);
896 // 3.3.4 Element Locally Valid (Element)
897 private void AssessElementLocallyValidElement (XmlSchemaElement element, string xsiNilValue)
899 XmlQualifiedName qname = new XmlQualifiedName (reader.LocalName, reader.NamespaceURI);
902 HandleError ("Element declaration is required for " + qname);
904 if (element.ActualIsAbstract)
905 HandleError ("Abstract element declaration was specified for " + qname);
907 if (!element.ActualIsNillable && xsiNilValue != null)
908 HandleError ("This element declaration is not nillable: " + qname);
910 // Note that 3.2.1 xsi:nil constraints are to be validated in
911 else if (xsiNilValue == "true") {
912 // AssessElementSchemaValidity() and ValidateCharacters()
914 if (element.ValidatedFixedValue != null)
915 HandleError ("Schema instance nil was specified, where the element declaration for " + qname + "has fixed value constraints.");
918 string xsiType = reader.GetAttribute ("type", XmlSchema.InstanceNamespace);
919 if (xsiType != null) {
920 context.LocalTypeDefinition = GetLocalTypeDefinition (xsiType);
921 AssessLocalTypeDerivationOK (context.LocalTypeDefinition, element.ElementType, element.BlockResolved);
924 context.LocalTypeDefinition = null;
926 // 5 Not all things cannot be assessed here.
927 // It is common to 5.1 and 5.2
928 if (element.ElementType != null)
929 AssessStartElementLocallyValidType (SchemaType);
931 // 6. should be out from here.
932 // See invokation of AssessStartIdentityConstraints().
934 // 7 is going to be validated in Read() (in case of xmlreader's EOF).
937 // 3.3.4 Element Locally Valid (Type)
938 private void AssessStartElementLocallyValidType (object schemaType)
940 if (schemaType == null) { // 1.
941 HandleError ("Schema type does not exist.");
944 XmlSchemaComplexType cType = schemaType as XmlSchemaComplexType;
945 XmlSchemaSimpleType sType = schemaType as XmlSchemaSimpleType;
948 while (reader.MoveToNextAttribute ()) {
949 if (reader.NamespaceURI == XmlNamespaceManager.XmlnsXmlns)
951 if (reader.NamespaceURI != XmlSchema.InstanceNamespace)
952 HandleError ("Current simple type cannot accept attributes other than schema instance namespace.");
953 switch (reader.LocalName) {
956 case "schemaLocation":
957 case "noNamespaceSchemaLocation":
960 HandleError ("Unknown schema instance namespace attribute: " + reader.LocalName);
964 reader.MoveToElement ();
965 // 3.1.2 and 3.1.3 cannot be assessed here.
966 } else if (cType != null) {
967 if (cType.IsAbstract) { // 2.
968 HandleError ("Target complex type is abstract.");
972 AssessElementLocallyValidComplexType (cType);
976 // 3.4.4 Element Locally Valid (Complex Type)
977 // TODO ("wild IDs constraints.")
978 private void AssessElementLocallyValidComplexType (XmlSchemaComplexType cType)
981 if (cType.IsAbstract)
982 HandleError ("Target complex type is abstract.");
984 // 2 (xsi:nil and content prohibition)
985 // See AssessStartElementSchemaValidity() and ValidateCharacters()
987 string elementNs = reader.NamespaceURI;
988 // 3. attribute uses and
990 while (reader.MoveToNextAttribute ()) {
991 if (reader.NamespaceURI == "http://www.w3.org/2000/xmlns/")
993 else if (reader.NamespaceURI == XmlSchema.InstanceNamespace)
995 XmlQualifiedName qname = new XmlQualifiedName (reader.LocalName, reader.NamespaceURI);
996 object attMatch = FindAttributeDeclaration (cType, qname, elementNs);
997 if (attMatch == null)
998 HandleError ("Attribute declaration was not found for " + qname);
1000 XmlSchemaAttribute attdecl = attMatch as XmlSchemaAttribute;
1001 if (attdecl == null) { // i.e. anyAttribute
1002 XmlSchemaAnyAttribute anyAttrMatch = attMatch as XmlSchemaAnyAttribute;
1004 AssessAttributeLocallyValidUse (attdecl);
1005 AssessAttributeLocallyValid (attdecl, true);
1009 reader.MoveToElement ();
1011 // Collect default attributes.
1013 // FIXME: FixedValue check maybe extraneous.
1014 foreach (DictionaryEntry entry in cType.AttributeUses) {
1015 XmlSchemaAttribute attr = (XmlSchemaAttribute) entry.Value;
1016 if (reader [attr.QualifiedName.Name, attr.QualifiedName.Namespace] == null) {
1017 if (attr.ValidatedUse == XmlSchemaUse.Required &&
1018 attr.ValidatedFixedValue == null)
1019 HandleError ("Required attribute " + attr.QualifiedName + " was not found.");
1020 else if (attr.ValidatedDefaultValue != null)
1021 defaultAttributesCache.Add (attr);
1022 else if (attr.ValidatedFixedValue != null)
1023 defaultAttributesCache.Add (attr);
1026 defaultAttributes = (XmlSchemaAttribute [])
1027 defaultAttributesCache.ToArray (typeof (XmlSchemaAttribute));
1028 context.DefaultAttributes = defaultAttributes;
1029 defaultAttributesCache.Clear ();
1030 // 5. wild IDs was already checked above.
1033 // Spec 3.10.4 Item Valid (Wildcard)
1034 private bool AttributeWildcardItemValid (XmlSchemaAnyAttribute anyAttr, XmlQualifiedName qname)
1036 if (anyAttr.HasValueAny)
1038 if (anyAttr.HasValueOther && (anyAttr.TargetNamespace == "" || reader.NamespaceURI != anyAttr.TargetNamespace))
1040 if (anyAttr.HasValueTargetNamespace && reader.NamespaceURI == anyAttr.TargetNamespace)
1042 if (anyAttr.HasValueLocal && reader.NamespaceURI == "")
1044 foreach (string ns in anyAttr.ResolvedNamespaces)
1045 if (ns == reader.NamespaceURI)
1050 private XmlSchemaObject FindAttributeDeclaration (XmlSchemaComplexType cType,
1051 XmlQualifiedName qname, string elementNs)
1053 XmlSchemaObject result = cType.AttributeUses [qname];
1056 if (cType.AttributeWildcard == null)
1059 if (!AttributeWildcardItemValid (cType.AttributeWildcard, qname))
1062 if (cType.AttributeWildcard.ResolvedProcessContents == XmlSchemaContentProcessing.Skip)
1063 return cType.AttributeWildcard;
1064 foreach (XmlSchema schema in schemas) {
1065 foreach (DictionaryEntry entry in schema.Attributes) {
1066 XmlSchemaAttribute attr = (XmlSchemaAttribute) entry.Value;
1067 if (attr.QualifiedName == qname)
1071 if (cType.AttributeWildcard.ResolvedProcessContents == XmlSchemaContentProcessing.Lax)
1072 return cType.AttributeWildcard;
1077 // 3.2.4 Attribute Locally Valid and 3.4.4 - 5.wildIDs
1079 private void AssessAttributeLocallyValid (XmlSchemaAttribute attr, bool checkWildIDs)
1082 switch (reader.NamespaceURI) {
1083 case XmlNamespaceManager.XmlnsXml:
1084 case XmlNamespaceManager.XmlnsXmlns:
1085 case XmlSchema.InstanceNamespace:
1089 if (attr.AttributeType == null)
1090 HandleError ("Attribute type is missing for " + attr.QualifiedName);
1091 XmlSchemaDatatype dt = attr.AttributeType as XmlSchemaDatatype;
1093 dt = ((XmlSchemaSimpleType) attr.AttributeType).Datatype;
1094 // It is a bit heavy process, so let's omit as long as possible ;-)
1095 if (dt != XmlSchemaSimpleType.AnySimpleType || attr.ValidatedFixedValue != null) {
1096 string normalized = dt.Normalize (reader.Value);
1097 object parsedValue = null;
1099 parsedValue = dt.ParseValue (normalized, reader.NameTable, this.ParserContext.NamespaceManager);
1100 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
1101 HandleError ("Attribute value is invalid against its data type " + dt.TokenizedType, ex);
1103 if (attr.ValidatedFixedValue != null && attr.ValidatedFixedValue != normalized)
1104 HandleError ("The value of the attribute " + attr.QualifiedName + " does not match with its fixed value.");
1105 // FIXME: this is extraneous checks in 3.2.4 Attribute Locally Valid.
1107 AssessEachAttributeIdentityConstraint (dt, normalized, parsedValue);
1111 private void AssessEachAttributeIdentityConstraint (XmlSchemaDatatype dt,
1112 string normalized, object parsedValue)
1114 // Get normalized value and (if required) parsedValue if missing.
1115 switch (dt.TokenizedType) {
1116 case XmlTokenizedType.IDREFS:
1117 if (normalized == null)
1118 normalized = dt.Normalize (reader.Value);
1119 if (parsedValue == null)
1120 parsedValue = dt.ParseValue (normalized, reader.NameTable, ParserContext.NamespaceManager);
1122 case XmlTokenizedType.ID:
1123 case XmlTokenizedType.IDREF:
1124 if (normalized == null)
1125 normalized = dt.Normalize (reader.Value);
1129 // Validate identity constraints.
1130 switch (dt.TokenizedType) {
1131 case XmlTokenizedType.ID:
1132 if (thisElementId != null)
1133 HandleError ("ID type attribute was already assigned in the containing element.");
1134 thisElementId = normalized;
1135 if (idList.Contains (normalized))
1136 HandleError ("Duplicate ID value was found.");
1138 idList.Add (normalized, normalized);
1140 case XmlTokenizedType.IDREF:
1141 if (missingIDReferences.Contains (normalized))
1142 missingIDReferences.Remove (normalized);
1144 missingIDReferences.Add (normalized);
1146 case XmlTokenizedType.IDREFS:
1147 foreach (string id in (string []) parsedValue) {
1148 if (missingIDReferences.Contains (id))
1149 missingIDReferences.Remove (id);
1151 missingIDReferences.Add (id);
1158 private void AssessAttributeLocallyValidUse (XmlSchemaAttribute attr)
1160 // TODO: value constraint check
1161 // This is extra check than spec 3.5.4
1162 if (attr.ValidatedUse == XmlSchemaUse.Prohibited)
1163 HandleError ("Attribute " + attr.QualifiedName + " is prohibited in this context.");
1166 private void AssessEndElementSchemaValidity ()
1168 if (childParticleState == null)
1169 childParticleState = context.ParticleState;
1170 ValidateEndElementParticle (); // validate against childrens' state.
1172 if (shouldValidateCharacters) {
1173 ValidateEndCharacters ();
1174 shouldValidateCharacters = false;
1177 // 3.3.4 Assess ElementLocallyValidElement 5: value constraints.
1178 // 3.3.4 Assess ElementLocallyValidType 3.1.3. = StringValid(3.14.4)
1179 // => ValidateEndCharacters().
1181 // Reset Identity constraints.
1182 for (int i = 0; i < keyTables.Count; i++) {
1183 XsdKeyTable keyTable = this.keyTables [i] as XsdKeyTable;
1184 if (keyTable.StartDepth == reader.Depth) {
1185 EndIdentityValidation (keyTable);
1187 for (int k = 0; k < keyTable.Entries.Count; k++) {
1188 XsdKeyEntry entry = keyTable.Entries [k] as XsdKeyEntry;
1189 // Remove finished (maybe key not found) entries.
1190 if (entry.StartDepth == reader.Depth) {
1192 keyTable.FinishedEntries.Add (entry);
1193 else if (entry.KeySequence.SourceSchemaIdentity is XmlSchemaKey)
1194 HandleError ("Key sequence is missing.");
1195 keyTable.Entries.RemoveAt (k);
1198 // Pop validated key depth to find two or more fields.
1200 foreach (XsdKeyEntryField kf in entry.KeyFields) {
1201 if (!kf.FieldFound && kf.FieldFoundDepth == reader.Depth) {
1202 kf.FieldFoundDepth = 0;
1203 kf.FieldFoundPath = null;
1210 for (int i = 0; i < keyTables.Count; i++) {
1211 XsdKeyTable keyseq = this.keyTables [i] as XsdKeyTable;
1212 if (keyseq.StartDepth == reader.Depth) {
1213 keyTables.RemoveAt (i);
1218 // Reset xsi:nil, if required.
1219 if (xsiNilDepth == reader.Depth)
1223 // 3.11.4 Identity Constraint Satisfied
1225 private void AssessStartIdentityConstraints ()
1227 tmpKeyrefPool.Clear ();
1228 if (context.Element != null && context.Element.Constraints.Count > 0) {
1229 // (a) Create new key sequences, if required.
1230 foreach (XmlSchemaIdentityConstraint ident in context.Element.Constraints) {
1231 XsdKeyTable seq = CreateNewKeyTable (ident);
1232 if (ident is XmlSchemaKeyref)
1233 tmpKeyrefPool.Add (seq);
1237 // (b) Evaluate current key sequences.
1238 foreach (XsdKeyTable seq in this.keyTables) {
1239 if (seq.SelectorMatches (this.elementQNameStack, reader) != null) {
1240 // creates and registers new entry.
1241 XsdKeyEntry entry = new XsdKeyEntry (seq, reader);
1242 seq.Entries.Add (entry);
1246 // (c) Evaluate field paths.
1247 foreach (XsdKeyTable seq in this.keyTables) {
1248 // If possible, create new field entry candidates.
1249 for (int i = 0; i < seq.Entries.Count; i++) {
1250 XsdKeyEntry entry = seq.Entries [i] as XsdKeyEntry;
1251 // if (entry.KeyFound)
1252 // FIXME: it should not be skipped for multiple key check!!
1255 entry.FieldMatches (this.elementQNameStack, this);
1256 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
1257 HandleError ("Identity field value is invalid against its data type.", ex);
1263 private XsdKeyTable CreateNewKeyTable (XmlSchemaIdentityConstraint ident)
1265 XsdKeyTable seq = new XsdKeyTable (ident, this);
1266 seq.StartDepth = reader.Depth;
1267 XmlSchemaKeyref keyref = ident as XmlSchemaKeyref;
1268 this.keyTables.Add (seq);
1272 private void EndIdentityValidation (XsdKeyTable seq)
1274 ArrayList errors = new ArrayList ();
1275 foreach (XsdKeyEntry entry in seq./*NotFound*/Entries) {
1278 if (seq.SourceSchemaIdentity is XmlSchemaKey)
1279 errors.Add ("line " + entry.SelectorLineNumber + "position " + entry.SelectorLinePosition);
1281 if (errors.Count > 0)
1282 HandleError ("Invalid identity constraints were found. Key was not found. "
1283 + String.Join (", ", errors.ToArray (typeof (string)) as string []));
1286 // Find reference target
1287 XmlSchemaKeyref xsdKeyref = seq.SourceSchemaIdentity as XmlSchemaKeyref;
1288 if (xsdKeyref != null) {
1289 for (int i = this.keyTables.Count - 1; i >= 0; i--) {
1290 XsdKeyTable target = this.keyTables [i] as XsdKeyTable;
1291 if (target.SourceSchemaIdentity == xsdKeyref.Target) {
1292 seq.ReferencedKey = target;
1293 foreach (XsdKeyEntry entry in seq.FinishedEntries) {
1294 foreach (XsdKeyEntry targetEntry in target.FinishedEntries) {
1295 if (entry.CompareIdentity (targetEntry)) {
1296 entry.KeyRefFound = true;
1303 if (seq.ReferencedKey == null)
1304 HandleError ("Target key was not found.");
1305 foreach (XsdKeyEntry entry in seq.FinishedEntries) {
1306 if (!entry.KeyRefFound)
1307 errors.Add (" line " + entry.SelectorLineNumber + ", position " + entry.SelectorLinePosition);
1309 if (errors.Count > 0)
1310 HandleError ("Invalid identity constraints were found. Referenced key was not found: "
1311 + String.Join (" / ", errors.ToArray (typeof (string)) as string []));
1315 // Overrided Methods
1317 public override void Close ()
1322 public override string GetAttribute (int i)
1324 switch (reader.NodeType) {
1325 case XmlNodeType.XmlDeclaration:
1326 case XmlNodeType.DocumentType:
1327 return reader.GetAttribute (i);
1330 if (reader.AttributeCount > i)
1331 reader.GetAttribute (i);
1332 int defIdx = i - nonDefaultAttributeCount;
1333 if (i < AttributeCount)
1334 return defaultAttributes [defIdx].DefaultValue;
1336 throw new ArgumentOutOfRangeException ("i", i, "Specified attribute index is out of range.");
1339 public override string GetAttribute (string name)
1341 switch (reader.NodeType) {
1342 case XmlNodeType.XmlDeclaration:
1343 case XmlNodeType.DocumentType:
1344 return reader.GetAttribute (name);
1347 string value = reader.GetAttribute (name);
1351 XmlQualifiedName qname = SplitQName (name);
1352 return GetDefaultAttribute (qname.Name, qname.Namespace);
1355 private XmlQualifiedName SplitQName (string name)
1357 if (!XmlChar.IsName (name))
1358 throw new ArgumentException ("Invalid name was specified.", "name");
1360 Exception ex = null;
1361 XmlQualifiedName qname = XmlSchemaUtil.ToQName (reader, name, out ex);
1363 return XmlQualifiedName.Empty;
1368 public override string GetAttribute (string localName, string ns)
1370 switch (reader.NodeType) {
1371 case XmlNodeType.XmlDeclaration:
1372 case XmlNodeType.DocumentType:
1373 return reader.GetAttribute (localName, ns);
1376 string value = reader.GetAttribute (localName, ns);
1380 return GetDefaultAttribute (localName, ns);
1383 private string GetDefaultAttribute (string localName, string ns)
1385 int idx = this.FindDefaultAttribute (localName, ns);
1388 string value = defaultAttributes [idx].ValidatedDefaultValue;
1390 value = defaultAttributes [idx].ValidatedFixedValue;
1394 private int FindDefaultAttribute (string localName, string ns)
1396 for (int i = 0; i < this.defaultAttributes.Length; i++) {
1397 XmlSchemaAttribute attr = defaultAttributes [i];
1398 if (attr.QualifiedName.Name == localName &&
1399 (ns == null || attr.QualifiedName.Namespace == ns))
1405 bool IXmlLineInfo.HasLineInfo ()
1407 return readerLineInfo != null && readerLineInfo.HasLineInfo ();
1410 public override string LookupNamespace (string prefix)
1412 return reader.LookupNamespace (prefix);
1415 public override void MoveToAttribute (int i)
1417 switch (reader.NodeType) {
1418 case XmlNodeType.XmlDeclaration:
1419 case XmlNodeType.DocumentType:
1420 reader.MoveToAttribute (i);
1424 currentQName = null;
1425 if (i < this.nonDefaultAttributeCount) {
1426 reader.MoveToAttribute (i);
1427 this.currentDefaultAttribute = -1;
1428 this.defaultAttributeConsumed = false;
1431 if (i < AttributeCount) {
1432 this.currentDefaultAttribute = i - nonDefaultAttributeCount;
1433 this.defaultAttributeConsumed = false;
1436 throw new ArgumentOutOfRangeException ("i", i, "Attribute index is out of range.");
1439 public override bool MoveToAttribute (string name)
1441 switch (reader.NodeType) {
1442 case XmlNodeType.XmlDeclaration:
1443 case XmlNodeType.DocumentType:
1444 return reader.MoveToAttribute (name);
1447 currentQName = null;
1448 bool b = reader.MoveToAttribute (name);
1450 this.currentDefaultAttribute = -1;
1451 this.defaultAttributeConsumed = false;
1455 return MoveToDefaultAttribute (name, null);
1458 public override bool MoveToAttribute (string localName, string ns)
1460 switch (reader.NodeType) {
1461 case XmlNodeType.XmlDeclaration:
1462 case XmlNodeType.DocumentType:
1463 return reader.MoveToAttribute (localName, ns);
1466 currentQName = null;
1467 bool b = reader.MoveToAttribute (localName, ns);
1469 this.currentDefaultAttribute = -1;
1470 this.defaultAttributeConsumed = false;
1474 return MoveToDefaultAttribute (localName, ns);
1477 private bool MoveToDefaultAttribute (string localName, string ns)
1479 int idx = this.FindDefaultAttribute (localName, ns);
1482 currentDefaultAttribute = idx;
1483 defaultAttributeConsumed = false;
1487 public override bool MoveToElement ()
1489 currentDefaultAttribute = -1;
1490 defaultAttributeConsumed = false;
1491 currentQName = null;
1492 return reader.MoveToElement ();
1495 public override bool MoveToFirstAttribute ()
1497 switch (reader.NodeType) {
1498 case XmlNodeType.XmlDeclaration:
1499 case XmlNodeType.DocumentType:
1500 return reader.MoveToFirstAttribute ();
1503 currentQName = null;
1504 if (this.nonDefaultAttributeCount > 0) {
1505 bool b = reader.MoveToFirstAttribute ();
1507 currentDefaultAttribute = -1;
1508 defaultAttributeConsumed = false;
1513 if (this.defaultAttributes.Length > 0) {
1514 currentDefaultAttribute = 0;
1515 defaultAttributeConsumed = false;
1522 public override bool MoveToNextAttribute ()
1524 switch (reader.NodeType) {
1525 case XmlNodeType.XmlDeclaration:
1526 case XmlNodeType.DocumentType:
1527 return reader.MoveToNextAttribute ();
1530 currentQName = null;
1531 if (currentDefaultAttribute >= 0) {
1532 if (defaultAttributes.Length == currentDefaultAttribute + 1)
1534 currentDefaultAttribute++;
1535 defaultAttributeConsumed = false;
1539 bool b = reader.MoveToNextAttribute ();
1541 currentDefaultAttribute = -1;
1542 defaultAttributeConsumed = false;
1546 if (defaultAttributes.Length > 0) {
1547 currentDefaultAttribute = 0;
1548 defaultAttributeConsumed = false;
1555 private void ExamineAdditionalSchema ()
1557 XmlSchema schema = null;
1558 string schemaLocation = reader.GetAttribute ("schemaLocation", XmlSchema.InstanceNamespace);
1559 if (schemaLocation != null) {
1560 string [] tmp = null;
1562 schemaLocation = XmlSchemaDatatype.FromName ("token").Normalize (schemaLocation);
1563 tmp = schemaLocation.Split (XmlChar.WhitespaceChars);
1564 } catch (Exception ex) {
1565 HandleError ("Invalid schemaLocation attribute format.", ex, true);
1566 tmp = new string [0];
1568 if (tmp.Length % 2 != 0)
1569 HandleError ("Invalid schemaLocation attribute format.");
1570 for (int i = 0; i < tmp.Length; i += 2) {
1573 absUri = new Uri ((this.BaseURI != "" ? new Uri (BaseURI) : null), tmp [i + 1]);
1574 XmlTextReader xtr = new XmlTextReader (absUri.ToString ());
1575 schema = XmlSchema.Read (xtr, null);
1576 } catch (Exception) { // FIXME: (wishlist) It is bad manner ;-(
1577 HandleError ("Could not resolve schema location URI: " + absUri, null, true);
\r
1580 if (schema.TargetNamespace == null)
1581 schema.TargetNamespace = tmp [i];
1582 else if (schema.TargetNamespace != tmp [i])
1583 HandleError ("Specified schema has different target namespace.");
1586 if (schema != null) {
1588 schemas.Add (schema, resolver);
1589 } catch (XmlSchemaException ex) {
1594 string noNsSchemaLocation = reader.GetAttribute ("noNamespaceSchemaLocation", XmlSchema.InstanceNamespace);
1595 if (noNsSchemaLocation != null) {
1598 absUri = new Uri ((this.BaseURI != "" ? new Uri (BaseURI) : null), noNsSchemaLocation);
1599 XmlTextReader xtr = new XmlTextReader (absUri.ToString ());
1600 schema = XmlSchema.Read (xtr, null);
1601 } catch (Exception) { // FIXME: (wishlist) It is bad manner ;-(
1602 HandleError ("Could not resolve schema location URI: " + absUri, null, true);
\r
1604 if (schema != null && schema.TargetNamespace != null)
1605 HandleError ("Specified schema has different target namespace.");
1607 if (schema != null) {
1609 schema.Compile (ValidationEventHandler, resolver);
1610 schemas.Add (schema);
1611 } catch (XmlSchemaException ex) {
1617 public override bool Read ()
1619 nonDefaultAttributeCount = 0;
1620 currentDefaultAttribute = -1;
1621 defaultAttributeConsumed = false;
1622 currentQName = null;
1623 thisElementId = null;
1624 defaultAttributes = new XmlSchemaAttribute [0];
1626 elementQNameStack.RemoveAt (elementQNameStack.Count - 1);
1630 bool result = reader.Read ();
1631 // 3.3.4 ElementLocallyValidElement 7 = Root Valid.
1632 if (!result && missingIDReferences.Count > 0)
1633 HandleError ("There are missing ID references: " +
1635 this.missingIDReferences.ToArray (typeof (string)) as string []));
1637 switch (reader.NodeType) {
1638 case XmlNodeType.XmlDeclaration:
1639 this.nonDefaultAttributeCount = reader.AttributeCount;
1641 case XmlNodeType.Element:
1642 nonDefaultAttributeCount = reader.AttributeCount;
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;
1805 internal class XsdValidityState
1807 ArrayList currentParticles = new ArrayList ();
1808 ArrayList occured = new ArrayList ();
1809 Hashtable xsAllConsumed = new Hashtable ();
1810 XmlSchemaParticle parciele;
1813 public XsdValidityState (XmlSchemaParticle particle)
1815 this.parciele = particle;
1816 currentParticles.Add (particle);