2 // XmlSchemaValidator.cs
5 // Atsushi Enomoto <atsushi@ximian.com>
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 // - There is no assurance that xsi:type precedes to any other attributes,
34 // or xsi:type is not handled.
35 // - There is no SourceUri provision.
41 using System.Collections;
45 using Mono.Xml.Schema;
47 using QName = System.Xml.XmlQualifiedName;
48 using Form = System.Xml.Schema.XmlSchemaForm;
49 using Use = System.Xml.Schema.XmlSchemaUse;
50 using ContentType = System.Xml.Schema.XmlSchemaContentType;
51 using Validity = System.Xml.Schema.XmlSchemaValidity;
52 using ValidationFlags = System.Xml.Schema.XmlSchemaValidationFlags;
53 using ContentProc = System.Xml.Schema.XmlSchemaContentProcessing;
54 using SOMList = System.Xml.Schema.XmlSchemaObjectCollection;
55 using SOMObject = System.Xml.Schema.XmlSchemaObject;
56 using XsElement = System.Xml.Schema.XmlSchemaElement;
57 using XsAttribute = System.Xml.Schema.XmlSchemaAttribute;
58 using AttrGroup = System.Xml.Schema.XmlSchemaAttributeGroup;
59 using AttrGroupRef = System.Xml.Schema.XmlSchemaAttributeGroupRef;
60 using XsDatatype = System.Xml.Schema.XmlSchemaDatatype;
61 using SimpleType = System.Xml.Schema.XmlSchemaSimpleType;
62 using ComplexType = System.Xml.Schema.XmlSchemaComplexType;
63 using SimpleModel = System.Xml.Schema.XmlSchemaSimpleContent;
64 using SimpleExt = System.Xml.Schema.XmlSchemaSimpleContentExtension;
65 using SimpleRst = System.Xml.Schema.XmlSchemaSimpleContentRestriction;
66 using ComplexModel = System.Xml.Schema.XmlSchemaComplexContent;
67 using ComplexExt = System.Xml.Schema.XmlSchemaComplexContentExtension;
68 using ComplexRst = System.Xml.Schema.XmlSchemaComplexContentRestriction;
69 using SimpleTypeRest = System.Xml.Schema.XmlSchemaSimpleTypeRestriction;
70 using SimpleTypeList = System.Xml.Schema.XmlSchemaSimpleTypeList;
71 using SimpleTypeUnion = System.Xml.Schema.XmlSchemaSimpleTypeUnion;
72 using SchemaFacet = System.Xml.Schema.XmlSchemaFacet;
73 using LengthFacet = System.Xml.Schema.XmlSchemaLengthFacet;
74 using MinLengthFacet = System.Xml.Schema.XmlSchemaMinLengthFacet;
75 using Particle = System.Xml.Schema.XmlSchemaParticle;
76 using Sequence = System.Xml.Schema.XmlSchemaSequence;
77 using Choice = System.Xml.Schema.XmlSchemaChoice;
78 using ValException = System.Xml.Schema.XmlSchemaValidationException;
81 namespace System.Xml.Schema
83 public sealed class XmlSchemaValidator
92 static readonly XsAttribute [] emptyAttributeArray =
95 public XmlSchemaValidator (
96 XmlNameTable nameTable,
98 IXmlNamespaceResolver nsResolver,
99 ValidationFlags options)
101 this.nameTable = nameTable;
102 this.schemas = schemas;
103 this.nsResolver = nsResolver;
104 this.options = options;
109 // XmlReader/XPathNavigator themselves
110 object nominalEventSender;
111 IXmlLineInfo lineInfo;
112 IXmlNamespaceResolver nsResolver;
115 // These fields will be from XmlReaderSettings or
116 // XPathNavigator.CheckValidity(). BTW, I think we could
117 // implement XPathNavigator.CheckValidity() with
118 // XsdValidatingReader.
119 XmlNameTable nameTable;
120 XmlSchemaSet schemas;
121 XmlResolver xmlResolver = new XmlUrlResolver ();
123 // "partialValidationType". but not sure how it will be used.
126 // It is perhaps from XmlReaderSettings, but XPathNavigator
128 ValidationFlags options;
131 Transition transition;
132 XsdParticleStateManager state;
134 ArrayList occuredAtts = new ArrayList ();
135 XsAttribute [] defaultAttributes = emptyAttributeArray;
136 ArrayList defaultAttributesCache = new ArrayList ();
138 #region ID Constraints
139 XsdIDManager idManager = new XsdIDManager ();
142 #region Key Constraints
143 ArrayList keyTables = new ArrayList ();
144 ArrayList currentKeyFieldConsumers = new ArrayList ();
145 ArrayList tmpKeyrefPool;
147 ArrayList elementQNameStack = new ArrayList ();
149 StringBuilder storedCharacters = new StringBuilder ();
150 bool shouldValidateCharacters;
153 int xsiNilDepth = -1;
154 int skipValidationDepth = -1;
156 SOMObject currentType;
161 #region Public properties
163 // Settable Properties
165 // IMHO It should just be an event that fires another event.
166 public event ValidationEventHandler ValidationEventHandler;
168 public object ValidationEventSender {
169 get { return nominalEventSender; }
170 set { nominalEventSender = value; }
173 // (kinda) Construction Properties
175 public IXmlLineInfo LineInfoProvider {
176 get { return lineInfo; }
177 set { lineInfo = value; }
180 public XmlResolver XmlResolver {
181 set { xmlResolver = value; }
184 public Uri SourceUri {
185 get { return sourceUri; }
186 set { sourceUri = value; }
190 #region Private properties
192 private string BaseUri {
193 get { return sourceUri != null ? sourceUri.AbsoluteUri : String.Empty; }
196 private XsdValidationContext Context {
197 get { return state.Context; }
200 private bool IgnoreWarnings {
201 get { return (options & ValidationFlags
202 .ReportValidationWarnings) == 0; }
205 private bool IgnoreIdentity {
206 get { return (options & ValidationFlags
207 .ProcessIdentityConstraints) == 0; }
212 #region Public methods
216 public XmlSchemaAttribute [] GetExpectedAttributes ()
218 ComplexType cType = Context.ActualType as ComplexType;
220 return emptyAttributeArray;
221 ArrayList al = new ArrayList ();
222 foreach (DictionaryEntry entry in cType.AttributeUses)
223 if (!occuredAtts.Contains ((QName) entry.Key))
224 al.Add (entry.Value);
225 return (XsAttribute [])
226 al.ToArray (typeof (XsAttribute));
229 private void CollectAtomicParticles (XmlSchemaParticle p,
232 if (p is XmlSchemaGroupBase) {
233 foreach (XmlSchemaParticle c in
234 ((XmlSchemaGroupBase) p).Items)
235 CollectAtomicParticles (c, al);
241 [MonoTODO ("Need some tests.")]
242 // Its behavior is not obvious. For example, it does not
243 // contain groups (xs:sequence/xs:choice/xs:all). Since it
244 // might contain xs:any, it could not be of type element[].
245 public XmlSchemaParticle [] GetExpectedParticles ()
247 ArrayList al = new ArrayList ();
248 Context.State.GetExpectedParticles (al);
249 ArrayList ret = new ArrayList ();
251 foreach (XmlSchemaParticle p in al)
252 CollectAtomicParticles (p, ret);
254 return (XmlSchemaParticle []) ret.ToArray (
255 typeof (XmlSchemaParticle));
258 public void GetUnspecifiedDefaultAttributes (ArrayList list)
260 if (transition != Transition.StartTag)
261 throw new InvalidOperationException ("Method 'GetUnsoecifiedDefaultAttributes' works only when the validator state is inside a start tag.");
262 foreach (XmlSchemaAttribute attr
263 in GetExpectedAttributes ())
264 if (attr.ValidatedDefaultValue != null || attr.ValidatedFixedValue != null)
267 list.AddRange (defaultAttributes);
272 public void AddSchema (XmlSchema schema)
274 schemas.Add (schema);
278 public void Initialize ()
283 public void Initialize (SOMObject startType)
285 this.startType = startType;
286 transition = Transition.Content;
287 state = new XsdParticleStateManager ();
288 if (!schemas.IsCompiled)
292 // It must be called at the end of the validation (to check
293 // identity constraints etc.).
294 public void EndValidation ()
296 CheckState (Transition.Content);
297 transition = Transition.Finished;
299 if (schemas.Count == 0)
303 throw new InvalidOperationException (String.Format ("There are {0} open element(s). ValidateEndElement() must be called for each open element.", depth));
305 // 3.3.4 ElementLocallyValidElement 7 = Root Valid.
306 if (!IgnoreIdentity &&
307 idManager.HasMissingIDReferences ())
308 HandleError ("There are missing ID references: " + idManager.GetMissingIDString ());
311 // I guess it is for validation error recovery
312 [MonoTODO ("Find out how XmlSchemaInfo is used.")]
313 public void SkipToEndElement (XmlSchemaInfo info)
315 CheckState (Transition.Content);
316 if (schemas.Count == 0)
321 public object ValidateAttribute (
324 string attributeValue,
327 return ValidateAttribute (localName, ns,
328 delegate () { return info.SchemaType.Datatype.ParseValue (attributeValue, nameTable, nsResolver); },
332 // I guess this weird XmlValueGetter is for such case that
333 // value might not be required (and thus it improves
334 // performance in some cases. Doh).
336 // The return value is typed primitive, is possible.
338 public object ValidateAttribute (
341 XmlValueGetter attributeValue,
344 CheckState (Transition.StartTag);
346 QName qname = new QName (localName, ns);
347 if (occuredAtts.Contains (qname))
348 throw new InvalidOperationException (String.Format ("Attribute '{0}' has already been validated in the same element.", qname));
349 occuredAtts.Add (qname);
351 if (ns == XmlNamespaceManager.XmlnsXmlns)
354 if (schemas.Count == 0)
357 // 3.3.4 Element Locally Valid (Type) - attribute
358 if (Context.ActualType is ComplexType)
359 return AssessAttributeElementLocallyValidType (localName, ns, attributeValue, info);
361 HandleError ("Current simple type cannot accept attributes other than schema instance namespace.");
366 public void ValidateElement (
371 ValidateElement (localName, ns, info, null, null, null, null);
374 public void ValidateElement (
380 string schemaLocation,
381 string noNsSchemaLocation)
383 CheckState (Transition.Content);
384 transition = Transition.StartTag;
386 if (schemaLocation != null)
387 HandleSchemaLocation (schemaLocation);
388 if (noNsSchemaLocation != null)
389 HandleNoNSSchemaLocation (noNsSchemaLocation);
391 elementQNameStack.Add (new XmlQualifiedName (localName, ns));
393 if (schemas.Count == 0)
396 #region ID Constraints
398 idManager.OnStartElement ();
400 defaultAttributes = emptyAttributeArray;
402 // If there is no schema information, then no validation is performed.
403 if (skipValidationDepth < 0 || depth <= skipValidationDepth) {
404 if (shouldValidateCharacters)
405 ValidateEndSimpleContent (null);
407 AssessOpenStartElementSchemaValidity (localName, ns);
411 HandleXsiNil (xsiNil, info);
413 HandleXsiType (xsiType);
415 shouldValidateCharacters = true;
418 info.IsNil = xsiNilDepth >= 0;
419 info.SchemaElement = Context.Element;
420 info.SchemaType = Context.ActualSchemaType;
421 info.SchemaAttribute = null;
422 info.IsDefault = false;
423 info.MemberType = null;
424 // FIXME: supply Validity (really useful?)
428 public object ValidateEndElement (XmlSchemaInfo info)
430 return ValidateEndElement (info, null);
433 // The return value is typed primitive, if supplied.
434 // Parameter 'var' seems to be converted into the type
435 // represented by current simple content type. (try passing
436 // some kind of object to this method to check the behavior.)
438 [MonoTODO ("Handle 'var' parameter.")]
439 public object ValidateEndElement (XmlSchemaInfo info,
442 // If it is going to validate an empty element, then
443 // first validate end of attributes.
444 if (transition == Transition.StartTag)
445 ValidateEndOfAttributes (info);
447 CheckState (Transition.Content);
449 elementQNameStack.RemoveAt (elementQNameStack.Count - 1);
451 if (schemas.Count == 0)
454 throw new InvalidOperationException ("There was no corresponding call to 'ValidateElement' method.");
459 if (depth == skipValidationDepth)
460 skipValidationDepth = -1;
461 else if (skipValidationDepth < 0 || depth <= skipValidationDepth)
462 ret = AssessEndElementSchemaValidity (info);
466 // StartTagCloseDeriv
467 // FIXME: fill validity inside this invocation.
468 public void ValidateEndOfAttributes (XmlSchemaInfo info)
471 CheckState (Transition.StartTag);
472 transition = Transition.Content;
473 if (schemas.Count == 0)
476 AssessCloseStartElementSchemaValidity (info);
478 occuredAtts.Clear ();
482 // LAMESPEC: It should also receive XmlSchemaInfo so that
483 // a validator application can receive simple type or
484 // or content type validation errors.
485 public void ValidateText (string value)
487 ValidateText (delegate () { return value; });
490 // TextDeriv ... without text. Maybe typed check is done by
491 // ValidateAtomicValue().
492 public void ValidateText (XmlValueGetter getter)
494 CheckState (Transition.Content);
495 if (schemas.Count == 0)
498 ComplexType ct = Context.ActualType as ComplexType;
499 if (ct != null && storedCharacters.Length > 0) {
500 switch (ct.ContentType) {
501 case XmlSchemaContentType.ElementOnly:
502 case XmlSchemaContentType.Empty:
503 HandleError ("Not allowed character content was found.");
508 ValidateCharacters (getter);
511 public void ValidateWhitespace (string value)
513 ValidateWhitespace (delegate () { return value; });
518 public void ValidateWhitespace (XmlValueGetter getter)
520 CheckState (Transition.Content);
521 if (schemas.Count == 0)
524 // throw new NotImplementedException ();
529 #region Error handling
531 private void HandleError (string message)
533 HandleError (message, null, false);
536 private void HandleError (
537 string message, Exception innerException)
539 HandleError (message, innerException, false);
542 private void HandleError (string message,
543 Exception innerException, bool isWarning)
545 if (isWarning && IgnoreWarnings)
548 ValException vex = new ValException (
549 message, nominalEventSender, BaseUri,
550 null, innerException);
551 HandleError (vex, isWarning);
554 private void HandleError (ValException exception)
556 HandleError (exception, false);
559 private void HandleError (ValException exception, bool isWarning)
561 if (isWarning && IgnoreWarnings)
564 if (ValidationEventHandler == null)
567 ValidationEventArgs e = new ValidationEventArgs (
570 isWarning ? XmlSeverityType.Warning :
571 XmlSeverityType.Error);
572 ValidationEventHandler (nominalEventSender, e);
577 private void CheckState (Transition expected)
579 if (transition != expected) {
580 if (transition == Transition.None)
581 throw new InvalidOperationException ("Initialize() must be called before processing validation.");
583 throw new InvalidOperationException (
584 String.Format ("Unexpected attempt to validation state transition from {0} to {1} was happened.",
590 private XsElement FindElement (string name, string ns)
592 return (XsElement) schemas.GlobalElements [new XmlQualifiedName (name, ns)];
595 private XmlSchemaType FindType (XmlQualifiedName qname)
597 return (XmlSchemaType) schemas.GlobalTypes [qname];
600 #region Type Validation
602 private void ValidateStartElementParticle (
603 string localName, string ns)
605 if (Context.State == null)
607 Context.XsiType = null;
608 state.CurrentElement = null;
609 Context.EvaluateStartElement (localName,
611 if (Context.IsInvalid)
612 HandleError ("Invalid start element: " + ns + ":" + localName);
614 Context.SetElement (state.CurrentElement);
617 private void AssessOpenStartElementSchemaValidity (
618 string localName, string ns)
620 // If the reader is inside xsi:nil (and failed
621 // on validation), then simply skip its content.
622 if (xsiNilDepth >= 0 && xsiNilDepth < depth)
623 HandleError ("Element item appeared, while current element context is nil.");
625 ValidateStartElementParticle (localName, ns);
627 // Create Validation Root, if not exist.
628 // [Schema Validity Assessment (Element) 1.1]
629 if (Context.Element == null) {
630 state.CurrentElement = FindElement (localName, ns);
631 Context.SetElement (state.CurrentElement);
634 #region Key Constraints
636 ValidateKeySelectors ();
637 ValidateKeyFields (false, xsiNilDepth == depth,
638 Context.ActualType, null, null, null);
642 private void AssessCloseStartElementSchemaValidity (XmlSchemaInfo info)
644 if (Context.XsiType != null)
645 AssessCloseStartElementLocallyValidType (info);
646 else if (Context.Element != null) {
647 // element locally valid is checked only when
648 // xsi:type does not exist.
649 AssessElementLocallyValidElement ();
650 if (Context.Element.ElementType != null)
651 AssessCloseStartElementLocallyValidType (info);
654 if (Context.Element == null) {
655 switch (state.ProcessContents) {
656 case ContentProc.Skip:
658 case ContentProc.Lax:
661 QName current = (QName) elementQNameStack [elementQNameStack.Count - 1];
662 if (Context.XsiType == null &&
663 (schemas.Contains (current.Namespace) ||
664 !schemas.MissedSubComponents (current.Namespace)))
665 HandleError ("Element declaration for " + current + " is missing.");
670 // Proceed to the next depth.
672 state.PushContext ();
674 XsdValidationState next = null;
675 if (state.ProcessContents == ContentProc.Skip)
676 skipValidationDepth = depth;
678 // create child particle state.
679 ComplexType xsComplexType = Context.ActualType as ComplexType;
680 if (xsComplexType != null)
681 next = state.Create (xsComplexType.ValidatableParticle);
682 else if (state.ProcessContents == ContentProc.Lax)
683 next = state.Create (XmlSchemaAny.AnyTypeContent);
685 next = state.Create (XmlSchemaParticle.Empty);
687 Context.State = next;
692 // It must be invoked after xsi:nil turned out not to be in
694 private void AssessElementLocallyValidElement ()
696 XsElement element = Context.Element;
697 XmlQualifiedName qname = (XmlQualifiedName) elementQNameStack [elementQNameStack.Count - 1];
700 HandleError ("Element declaration is required for " + qname);
702 if (element.ActualIsAbstract)
703 HandleError ("Abstract element declaration was specified for " + qname);
704 // 3. is checked inside ValidateAttribute().
707 // 3.3.4 Element Locally Valid (Type)
708 private void AssessCloseStartElementLocallyValidType (XmlSchemaInfo info)
710 object schemaType = Context.ActualType;
711 if (schemaType == null) { // 1.
712 HandleError ("Schema type does not exist.");
715 ComplexType cType = schemaType as ComplexType;
716 SimpleType sType = schemaType as SimpleType;
719 // Attributes are checked in ValidateAttribute().
720 } else if (cType != null) {
721 // 3.2. Also, 2. is checked there.
722 AssessCloseStartElementLocallyValidComplexType (cType, info);
726 // 3.4.4 Element Locally Valid (Complex Type)
727 // FIXME: use SchemaInfo for somewhere (? it is passed to ValidateEndOfAttributes() for some reason)
728 private void AssessCloseStartElementLocallyValidComplexType (ComplexType cType, XmlSchemaInfo info)
731 if (cType.IsAbstract) {
732 HandleError ("Target complex type is abstract.");
736 // 2 (xsi:nil and content prohibition)
737 // See AssessStartElementSchemaValidity() and ValidateCharacters()
738 // 3. attribute uses and 5. wild IDs are handled at
739 // ValidateAttribute().
741 // Collect default attributes.
743 foreach (XsAttribute attr in GetExpectedAttributes ()) {
744 if (attr.ValidatedUse == XmlSchemaUse.Required &&
745 attr.ValidatedFixedValue == null)
746 HandleError ("Required attribute " + attr.QualifiedName + " was not found.");
747 else if (attr.ValidatedDefaultValue != null || attr.ValidatedFixedValue != null)
748 defaultAttributesCache.Add (attr);
750 if (defaultAttributesCache.Count == 0)
751 defaultAttributes = emptyAttributeArray;
753 defaultAttributes = (XsAttribute [])
754 defaultAttributesCache.ToArray (
755 typeof (XsAttribute));
756 defaultAttributesCache.Clear ();
757 // 5. wild IDs was already checked at ValidateAttribute().
761 private object AssessAttributeElementLocallyValidType (string localName, string ns, XmlValueGetter getter, XmlSchemaInfo info)
763 ComplexType cType = Context.ActualType as ComplexType;
764 XmlQualifiedName qname = new XmlQualifiedName (localName, ns);
765 // including 3.10.4 Item Valid (Wildcard)
766 XmlSchemaObject attMatch = XmlSchemaUtil.FindAttributeDeclaration (ns, schemas, cType, qname);
767 if (attMatch == null)
768 HandleError ("Attribute declaration was not found for " + qname);
769 XsAttribute attdecl = attMatch as XsAttribute;
770 if (attdecl != null) {
771 AssessAttributeLocallyValidUse (attdecl);
772 return AssessAttributeLocallyValid (attdecl, info, getter);
773 } // otherwise anyAttribute or null.
777 // 3.2.4 Attribute Locally Valid and 3.4.4
778 private object AssessAttributeLocallyValid (XsAttribute attr, XmlSchemaInfo info, XmlValueGetter getter)
781 if (attr.AttributeType == null)
782 HandleError ("Attribute type is missing for " + attr.QualifiedName);
783 XsDatatype dt = attr.AttributeType as XsDatatype;
785 dt = ((SimpleType) attr.AttributeType).Datatype;
786 // It is a bit heavy process, so let's omit as long as possible ;-)
787 if (dt != SimpleType.AnySimpleType || attr.ValidatedFixedValue != null) {
788 object parsedValue = null;
790 parsedValue = getter ();
791 } catch (Exception ex) { // It is inevitable and bad manner.
792 HandleError ("Attribute value is invalid against its data type " + dt.TokenizedType, ex);
794 XmlSchemaType type = info != null ? info.SchemaType : null;
795 if (attr.ValidatedFixedValue != null &&
796 !XmlSchemaUtil.IsSchemaDatatypeEquals (
797 attr.AttributeSchemaType.Datatype as XsdAnySimpleType, attr.ValidatedFixedTypedValue, type != null ? type.Datatype as XsdAnySimpleType : null, parsedValue)) {
798 HandleError ("The value of the attribute " + attr.QualifiedName + " does not match with its fixed value.");
799 parsedValue = attr.ValidatedFixedTypedValue;
801 #region ID Constraints
802 if (!IgnoreIdentity) {
803 string error = idManager.AssessEachAttributeIdentityConstraint (dt, parsedValue, ((QName) elementQNameStack [elementQNameStack.Count - 1]).Name);
809 #region Key Constraints
815 attr.QualifiedName.Name,
816 attr.QualifiedName.Namespace,
825 private void AssessAttributeLocallyValidUse (XsAttribute attr)
827 // This is extra check than spec 3.5.4
828 if (attr.ValidatedUse == XmlSchemaUse.Prohibited)
829 HandleError ("Attribute " + attr.QualifiedName + " is prohibited in this context.");
832 private object AssessEndElementSchemaValidity (
835 ValidateEndElementParticle (); // validate against childrens' state.
837 object ret = ValidateEndSimpleContent (info);
839 // 3.3.4 Assess ElementLocallyValidElement 5: value constraints.
840 // 3.3.4 Assess ElementLocallyValidType 3.1.3. = StringValid(3.14.4)
841 // => ValidateEndSimpleContent ().
843 #region Key Constraints
845 ValidateEndElementKeyConstraints ();
848 // Reset xsi:nil, if required.
849 if (xsiNilDepth == depth)
854 private void ValidateEndElementParticle ()
856 if (Context.State != null) {
857 if (!Context.EvaluateEndElement ()) {
858 HandleError ("Invalid end element. There are still required content items.");
864 // Utility for missing validation completion related to child items.
865 private void ValidateCharacters (XmlValueGetter getter)
867 if (xsiNilDepth >= 0 && xsiNilDepth < depth)
868 HandleError ("Element item appeared, while current element context is nil.");
870 if (shouldValidateCharacters)
871 storedCharacters.Append (getter ());
875 // Utility for missing validation completion related to child items.
876 private object ValidateEndSimpleContent (XmlSchemaInfo info)
879 if (shouldValidateCharacters)
880 ret = ValidateEndSimpleContentCore (info);
881 shouldValidateCharacters = false;
882 storedCharacters.Length = 0;
886 private object ValidateEndSimpleContentCore (XmlSchemaInfo info)
888 if (Context.ActualType == null)
891 string value = storedCharacters.ToString ();
894 if (value.Length == 0) {
895 // 3.3.4 Element Locally Valid (Element) 5.1.2
896 if (Context.Element != null) {
897 if (Context.Element.ValidatedDefaultValue != null)
898 value = Context.Element.ValidatedDefaultValue;
902 XsDatatype dt = Context.ActualType as XsDatatype;
903 SimpleType st = Context.ActualType as SimpleType;
908 ComplexType ct = Context.ActualType as ComplexType;
910 switch (ct.ContentType) {
911 case XmlSchemaContentType.ElementOnly:
912 case XmlSchemaContentType.Empty:
913 if (value.Length > 0)
914 HandleError ("Character content not allowed.");
920 // 3.3.4 Element Locally Valid (Element) :: 5.2.2.2. Fixed value constraints
921 if (Context.Element != null && Context.Element.ValidatedFixedValue != null)
922 if (value != Context.Element.ValidatedFixedValue)
923 HandleError ("Fixed value constraint was not satisfied.");
924 ret = AssessStringValid (st, dt, value);
927 #region Key Constraints
929 ValidateSimpleContentIdentity (dt, value);
932 shouldValidateCharacters = false;
935 info.IsNil = xsiNilDepth >= 0;
936 info.SchemaElement = null;
937 info.SchemaType = Context.ActualType as XmlSchemaType;
938 if (info.SchemaType == null)
939 info.SchemaType = XmlSchemaType.GetBuiltInSimpleType (dt.TypeCode);
940 info.SchemaAttribute = null;
941 info.IsDefault = false; // FIXME: might be true
942 info.MemberType = null; // FIXME: check
943 // FIXME: supply Validity (really useful?)
949 // 3.14.4 String Valid
950 private object AssessStringValid (SimpleType st,
951 XsDatatype dt, string value)
953 XsDatatype validatedDatatype = dt;
956 string normalized = validatedDatatype.Normalize (value);
958 XsDatatype itemDatatype;
959 SimpleType itemSimpleType;
960 switch (st.DerivedBy) {
961 case XmlSchemaDerivationMethod.List:
962 SimpleTypeList listContent = st.Content as SimpleTypeList;
963 values = normalized.Split (XmlChar.WhitespaceChars);
964 // LAMESPEC: Types of each element in
965 // the returned list might be
966 // inconsistent, so basically returning
967 // value does not make sense without
968 // explicit runtime type information
969 // for base primitive type.
970 object [] retValues = new object [values.Length];
971 itemDatatype = listContent.ValidatedListItemType as XsDatatype;
972 itemSimpleType = listContent.ValidatedListItemType as SimpleType;
973 for (int vi = 0; vi < values.Length; vi++) {
974 string each = values [vi];
975 if (each == String.Empty)
977 // validate against ValidatedItemType
978 if (itemDatatype != null) {
980 retValues [vi] = itemDatatype.ParseValue (each, nameTable, nsResolver);
981 } catch (Exception ex) { // It is inevitable and bad manner.
982 HandleError ("List type value contains one or more invalid values.", ex);
987 AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
991 case XmlSchemaDerivationMethod.Union:
992 SimpleTypeUnion union = st.Content as SimpleTypeUnion;
994 string each = normalized;
995 // validate against ValidatedItemType
997 foreach (object eachType in union.ValidatedTypes) {
998 itemDatatype = eachType as XsDatatype;
999 itemSimpleType = eachType as SimpleType;
1000 if (itemDatatype != null) {
1002 ret = itemDatatype.ParseValue (each, nameTable, nsResolver);
1003 } catch (Exception) { // It is inevitable and bad manner.
1009 ret = AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
1010 } catch (ValException) {
1018 HandleError ("Union type value contains one or more invalid values.");
1023 case XmlSchemaDerivationMethod.Restriction:
1024 SimpleTypeRest str = st.Content as SimpleTypeRest;
1027 /* Don't forget to validate against inherited type's facets
1028 * Could we simplify this by assuming that the basetype will also
1031 // mmm, will check later.
1032 SimpleType baseType = st.BaseXmlSchemaType as SimpleType;
1033 if (baseType != null) {
1034 ret = AssessStringValid (baseType, dt, value);
1036 if (!str.ValidateValueWithFacets (value, nameTable, nsResolver)) {
1037 HandleError ("Specified value was invalid against the facets.");
1041 validatedDatatype = st.Datatype;
1045 if (validatedDatatype != null) {
1047 ret = validatedDatatype.ParseValue (value, nameTable, nsResolver);
1048 } catch (Exception ex) { // It is inevitable and bad manner.
1049 HandleError (String.Format ("Invalidly typed data was specified."), ex);
1057 #region Key Constraints Validation
1058 private XsdKeyTable CreateNewKeyTable (XmlSchemaIdentityConstraint ident)
1060 XsdKeyTable seq = new XsdKeyTable (ident);
1061 seq.StartDepth = depth;
1062 this.keyTables.Add (seq);
1066 // 3.11.4 Identity Constraint Satisfied
1067 private void ValidateKeySelectors ()
1069 if (tmpKeyrefPool != null)
1070 tmpKeyrefPool.Clear ();
1071 if (Context.Element != null && Context.Element.Constraints.Count > 0) {
1072 // (a) Create new key sequences, if required.
1073 for (int i = 0; i < Context.Element.Constraints.Count; i++) {
1074 XmlSchemaIdentityConstraint ident = (XmlSchemaIdentityConstraint) Context.Element.Constraints [i];
1075 XsdKeyTable seq = CreateNewKeyTable (ident);
1076 if (ident is XmlSchemaKeyref) {
1077 if (tmpKeyrefPool == null)
1078 tmpKeyrefPool = new ArrayList ();
1079 tmpKeyrefPool.Add (seq);
1084 // (b) Evaluate current key sequences.
1085 for (int i = 0; i < keyTables.Count; i++) {
1086 XsdKeyTable seq = (XsdKeyTable) keyTables [i];
1087 if (seq.SelectorMatches (this.elementQNameStack, depth) != null) {
1088 // creates and registers new entry.
1089 XsdKeyEntry entry = new XsdKeyEntry (seq, depth, lineInfo);
1090 seq.Entries.Add (entry);
1095 private void ValidateKeyFields (bool isAttr, bool isNil, object schemaType, string attrName, string attrNs, XmlValueGetter getter)
1097 // (c) Evaluate field paths.
1098 for (int i = 0; i < keyTables.Count; i++) {
1099 XsdKeyTable seq = (XsdKeyTable) keyTables [i];
1100 // If possible, create new field entry candidates.
1101 for (int j = 0; j < seq.Entries.Count; j++) {
1103 seq.Entries [j].ProcessMatch (
1119 currentKeyFieldConsumers);
1120 } catch (ValException ex) {
1127 private void ProcessKeyEntryOne (XsdKeyEntry entry, bool isAttr, bool isNil, object schemaType, string attrName, string attrNs, XmlValueGetter getter)
1131 private void ValidateEndElementKeyConstraints ()
1133 // Reset Identity constraints.
1134 for (int i = 0; i < keyTables.Count; i++) {
1135 XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
1136 if (seq.StartDepth == depth) {
1137 ValidateEndKeyConstraint (seq);
1139 for (int k = 0; k < seq.Entries.Count; k++) {
1140 XsdKeyEntry entry = seq.Entries [k] as XsdKeyEntry;
1141 // Remove finished (maybe key not found) entries.
1142 if (entry.StartDepth == depth) {
1144 seq.FinishedEntries.Add (entry);
1145 else if (seq.SourceSchemaIdentity is XmlSchemaKey)
1146 HandleError ("Key sequence is missing.");
1147 seq.Entries.RemoveAt (k);
1150 // Pop validated key depth to find two or more fields.
1152 for (int j = 0; j < entry.KeyFields.Count; j++) {
1153 XsdKeyEntryField kf = entry.KeyFields [j];
1154 if (!kf.FieldFound && kf.FieldFoundDepth == depth) {
1155 kf.FieldFoundDepth = 0;
1156 kf.FieldFoundPath = null;
1163 for (int i = 0; i < keyTables.Count; i++) {
1164 XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
1165 if (seq.StartDepth == depth) {
1166 keyTables.RemoveAt (i);
1172 private void ValidateEndKeyConstraint (XsdKeyTable seq)
1174 ArrayList errors = new ArrayList ();
1175 for (int i = 0; i < seq.Entries.Count; i++) {
1176 XsdKeyEntry entry = (XsdKeyEntry) seq.Entries [i];
1179 if (seq.SourceSchemaIdentity is XmlSchemaKey)
1180 errors.Add ("line " + entry.SelectorLineNumber + "position " + entry.SelectorLinePosition);
1182 if (errors.Count > 0)
1183 HandleError ("Invalid identity constraints were found. Key was not found. "
1184 + String.Join (", ", errors.ToArray (typeof (string)) as string []));
1187 // Find reference target
1188 XmlSchemaKeyref xsdKeyref = seq.SourceSchemaIdentity as XmlSchemaKeyref;
1189 if (xsdKeyref != null) {
1190 for (int i = this.keyTables.Count - 1; i >= 0; i--) {
1191 XsdKeyTable target = this.keyTables [i] as XsdKeyTable;
1192 if (target.SourceSchemaIdentity == xsdKeyref.Target) {
1193 seq.ReferencedKey = target;
1194 for (int j = 0; j < seq.FinishedEntries.Count; j++) {
1195 XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [j];
1196 for (int k = 0; k < target.FinishedEntries.Count; k++) {
1197 XsdKeyEntry targetEntry = (XsdKeyEntry) target.FinishedEntries [k];
1198 if (entry.CompareIdentity (targetEntry)) {
1199 entry.KeyRefFound = true;
1206 if (seq.ReferencedKey == null)
1207 HandleError ("Target key was not found.");
1208 for (int i = 0; i < seq.FinishedEntries.Count; i++) {
1209 XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [i];
1210 if (!entry.KeyRefFound)
1211 errors.Add (" line " + entry.SelectorLineNumber + ", position " + entry.SelectorLinePosition);
1213 if (errors.Count > 0)
1214 HandleError ("Invalid identity constraints were found. Referenced key was not found: "
1215 + String.Join (" / ", errors.ToArray (typeof (string)) as string []));
1219 private void ValidateSimpleContentIdentity (
1220 XmlSchemaDatatype dt, string value)
1222 // Identity field value
1223 if (currentKeyFieldConsumers != null) {
1224 while (this.currentKeyFieldConsumers.Count > 0) {
1225 XsdKeyEntryField field = this.currentKeyFieldConsumers [0] as XsdKeyEntryField;
1226 if (field.Identity != null)
1227 HandleError ("Two or more identical field was found. Former value is '" + field.Identity + "' .");
1228 object identity = null; // This means empty value
1231 identity = dt.ParseValue (value, nameTable, nsResolver);
1232 } catch (Exception ex) { // It is inevitable and bad manner.
1233 HandleError ("Identity value is invalid against its data type " + dt.TokenizedType, ex);
1236 if (identity == null)
1239 if (!field.SetIdentityField (identity, depth == xsiNilDepth, dt as XsdAnySimpleType, depth, lineInfo))
1240 HandleError ("Two or more identical key value was found: '" + value + "' .");
1241 this.currentKeyFieldConsumers.RemoveAt (0);
1248 private object GetXsiType (string name)
1250 object xsiType = null;
1251 XmlQualifiedName typeQName =
1252 XmlQualifiedName.Parse (name, nsResolver);
1253 if (typeQName == ComplexType.AnyTypeName)
1254 xsiType = ComplexType.AnyType;
1255 else if (XmlSchemaUtil.IsBuiltInDatatypeName (typeQName))
1256 xsiType = XsDatatype.FromName (typeQName);
1258 xsiType = FindType (typeQName);
1262 private void HandleXsiType (string typename)
1264 XsElement element = Context.Element;
1265 object xsiType = GetXsiType (typename);
1266 if (xsiType == null) {
1267 HandleError ("The instance type was not found: " + typename);
1270 XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
1271 if (xsiSchemaType != null && Context.Element != null) {
1272 XmlSchemaType elemBaseType = element.ElementType as XmlSchemaType;
1273 if (elemBaseType != null && (xsiSchemaType.DerivedBy & elemBaseType.FinalResolved) != 0)
1274 HandleError ("The instance type is prohibited by the type of the context element.");
1275 if (elemBaseType != xsiType && (xsiSchemaType.DerivedBy & element.BlockResolved) != 0)
1276 HandleError ("The instance type is prohibited by the context element.");
1278 ComplexType xsiComplexType = xsiType as ComplexType;
1279 if (xsiComplexType != null && xsiComplexType.IsAbstract)
1280 HandleError ("The instance type is abstract: " + typename);
1282 // If current schema type exists, then this xsi:type must be
1283 // valid extension of that type. See 1.2.1.2.4.
1284 if (element != null) {
1285 AssessLocalTypeDerivationOK (xsiType, element.ElementType, element.BlockResolved);
1287 // See also ValidateEndOfAttributes().
1288 Context.XsiType = xsiType;
1292 // It is common to ElementLocallyValid::4 and SchemaValidityAssessment::1.2.1.2.4
1293 private void AssessLocalTypeDerivationOK (object xsiType, object baseType, XmlSchemaDerivationMethod flag)
1295 XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
1296 ComplexType baseComplexType = baseType as ComplexType;
1297 ComplexType xsiComplexType = xsiSchemaType as ComplexType;
1298 if (xsiType != baseType) {
1299 // Extracted (not extraneous) check for 3.4.6 TypeDerivationOK.
1300 if (baseComplexType != null)
1301 flag |= baseComplexType.BlockResolved;
1302 if (flag == XmlSchemaDerivationMethod.All) {
1303 HandleError ("Prohibited element type substitution.");
1305 } else if (xsiSchemaType != null && (flag & xsiSchemaType.DerivedBy) != 0) {
1306 HandleError ("Prohibited element type substitution.");
1311 if (xsiComplexType != null)
1313 xsiComplexType.ValidateTypeDerivationOK (baseType, null, null);
1314 } catch (ValException ex) {
1318 SimpleType xsiSimpleType = xsiType as SimpleType;
1319 if (xsiSimpleType != null) {
1321 xsiSimpleType.ValidateTypeDerivationOK (baseType, null, null, true);
1322 } catch (ValException ex) {
1326 else if (xsiType is XsDatatype) {
1330 HandleError ("Primitive data type cannot be derived type using xsi:type specification.");
1335 private void HandleXsiNil (string value, XmlSchemaInfo info)
1337 XsElement element = Context.Element;
1338 if (!element.ActualIsNillable) {
1339 HandleError (String.Format ("Current element '{0}' is not nillable and thus does not allow occurence of 'nil' attribute.", Context.Element.QualifiedName));
1342 value = value.Trim (XmlChar.WhitespaceChars);
1344 // Note that 3.2.1 xsi:nil constraints are to be
1345 // validated in AssessElementSchemaValidity() and
1346 // ValidateCharacters().
1347 if (value == "true") {
1348 if (element.ValidatedFixedValue != null)
1349 HandleError ("Schema instance nil was specified, where the element declaration for " + element.QualifiedName + "has fixed value constraints.");
1350 xsiNilDepth = depth;
1356 #region External schema resolution
1358 private XmlSchema ReadExternalSchema (string uri)
1360 Uri absUri = new Uri (SourceUri, uri.Trim (XmlChar.WhitespaceChars));
1361 XmlTextReader xtr = null;
1363 xtr = new XmlTextReader (absUri.ToString (),
1364 (Stream) xmlResolver.GetEntity (
1365 absUri, null, typeof (Stream)),
1367 return XmlSchema.Read (
1368 xtr, ValidationEventHandler);
1375 private void HandleSchemaLocation (string schemaLocation)
1377 if (xmlResolver == null)
1379 XmlSchema schema = null;
1380 bool schemaAdded = false;
1381 string [] tmp = null;
1383 schemaLocation = XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.Token).Datatype.ParseValue (schemaLocation, null, null) as string;
1384 tmp = schemaLocation.Split (XmlChar.WhitespaceChars);
1385 } catch (Exception ex) {
1386 HandleError ("Invalid schemaLocation attribute format.", ex, true);
1387 tmp = new string [0];
1389 if (tmp.Length % 2 != 0)
1390 HandleError ("Invalid schemaLocation attribute format.");
1391 for (int i = 0; i < tmp.Length; i += 2) {
1393 schema = ReadExternalSchema (tmp [i + 1]);
1394 } catch (Exception ex) { // It is inevitable and bad manner.
1395 HandleError ("Could not resolve schema location URI: " + schemaLocation, ex, true);
1398 if (schema.TargetNamespace == null)
1399 schema.TargetNamespace = tmp [i];
1400 else if (schema.TargetNamespace != tmp [i])
1401 HandleError ("Specified schema has different target namespace.");
1403 if (schema != null) {
1404 if (!schemas.Contains (schema.TargetNamespace)) {
1406 schemas.Add (schema);
1414 private void HandleNoNSSchemaLocation (string noNsSchemaLocation)
1416 if (xmlResolver == null)
1418 XmlSchema schema = null;
1419 bool schemaAdded = false;
1422 schema = ReadExternalSchema (noNsSchemaLocation);
1423 } catch (Exception ex) { // It is inevitable and bad manner.
1424 HandleError ("Could not resolve schema location URI: " + noNsSchemaLocation, ex, true);
1426 if (schema != null && schema.TargetNamespace != null)
1427 HandleError ("Specified schema has different target namespace.");
1429 if (schema != null) {
1430 if (!schemas.Contains (schema.TargetNamespace)) {
1432 schemas.Add (schema);