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 // LAMESPEC: XmlValueGetter is bogus by design because there
157 // is no way to get associated schema type for current value.
158 // Here XmlSchemaValidatingReader needs "current type"
159 // information to validate attribute values.
160 internal XmlSchemaDatatype CurrentAttributeType;
164 #region Public properties
166 // Settable Properties
168 // IMHO It should just be an event that fires another event.
169 public event ValidationEventHandler ValidationEventHandler;
171 public object ValidationEventSender {
172 get { return nominalEventSender; }
173 set { nominalEventSender = value; }
176 // (kinda) Construction Properties
178 public IXmlLineInfo LineInfoProvider {
179 get { return lineInfo; }
180 set { lineInfo = value; }
183 public XmlResolver XmlResolver {
184 set { xmlResolver = value; }
187 public Uri SourceUri {
188 get { return sourceUri; }
189 set { sourceUri = value; }
193 #region Private properties
195 private string BaseUri {
196 get { return sourceUri != null ? sourceUri.AbsoluteUri : String.Empty; }
199 private XsdValidationContext Context {
200 get { return state.Context; }
203 private bool IgnoreWarnings {
204 get { return (options & ValidationFlags
205 .ReportValidationWarnings) == 0; }
208 private bool IgnoreIdentity {
209 get { return (options & ValidationFlags
210 .ProcessIdentityConstraints) == 0; }
215 #region Public methods
219 public XmlSchemaAttribute [] GetExpectedAttributes ()
221 ComplexType cType = Context.ActualType as ComplexType;
223 return emptyAttributeArray;
224 ArrayList al = new ArrayList ();
225 foreach (DictionaryEntry entry in cType.AttributeUses)
226 if (!occuredAtts.Contains ((QName) entry.Key))
227 al.Add (entry.Value);
228 return (XsAttribute [])
229 al.ToArray (typeof (XsAttribute));
232 private void CollectAtomicParticles (XmlSchemaParticle p,
235 if (p is XmlSchemaGroupBase) {
236 foreach (XmlSchemaParticle c in
237 ((XmlSchemaGroupBase) p).Items)
238 CollectAtomicParticles (c, al);
244 [MonoTODO] // Need some tests.
245 // Its behavior is not obvious. For example, it does not
246 // contain groups (xs:sequence/xs:choice/xs:all). Since it
247 // might contain xs:any, it could not be of type element[].
248 public XmlSchemaParticle [] GetExpectedParticles ()
250 ArrayList al = new ArrayList ();
251 Context.State.GetExpectedParticles (al);
252 ArrayList ret = new ArrayList ();
254 foreach (XmlSchemaParticle p in al)
255 CollectAtomicParticles (p, ret);
257 return (XmlSchemaParticle []) ret.ToArray (
258 typeof (XmlSchemaParticle));
261 public void GetUnspecifiedDefaultAttributes (ArrayList defaultAttributeList)
263 if (defaultAttributeList == null)
264 throw new ArgumentNullException ("defaultAttributeList");
266 if (transition != Transition.StartTag)
267 throw new InvalidOperationException ("Method 'GetUnsoecifiedDefaultAttributes' works only when the validator state is inside a start tag.");
268 foreach (XmlSchemaAttribute attr
269 in GetExpectedAttributes ())
270 if (attr.ValidatedDefaultValue != null || attr.ValidatedFixedValue != null)
271 defaultAttributeList.Add (attr);
273 defaultAttributeList.AddRange (defaultAttributes);
278 public void AddSchema (XmlSchema schema)
281 throw new ArgumentNullException ("schema");
282 schemas.Add (schema);
286 public void Initialize ()
288 transition = Transition.Content;
289 state = new XsdParticleStateManager ();
290 if (!schemas.IsCompiled)
294 public void Initialize (SOMObject partialValidationType)
296 if (partialValidationType == null)
297 throw new ArgumentNullException ("partialValidationType");
298 this.startType = partialValidationType;
302 // It must be called at the end of the validation (to check
303 // identity constraints etc.).
304 public void EndValidation ()
306 CheckState (Transition.Content);
307 transition = Transition.Finished;
309 if (schemas.Count == 0)
313 throw new InvalidOperationException (String.Format ("There are {0} open element(s). ValidateEndElement() must be called for each open element.", depth));
315 // 3.3.4 ElementLocallyValidElement 7 = Root Valid.
316 if (!IgnoreIdentity &&
317 idManager.HasMissingIDReferences ())
318 HandleError ("There are missing ID references: " + idManager.GetMissingIDString ());
321 // I guess it is for validation error recovery
322 [MonoTODO] // FIXME: Find out how XmlSchemaInfo is used.
323 public void SkipToEndElement (XmlSchemaInfo info)
325 CheckState (Transition.Content);
326 if (schemas.Count == 0)
331 public object ValidateAttribute (
334 string attributeValue,
337 if (attributeValue == null)
338 throw new ArgumentNullException ("attributeValue");
339 return ValidateAttribute (localName, ns, delegate () { return attributeValue; }, info);
342 // I guess this weird XmlValueGetter is for such case that
343 // value might not be required (and thus it improves
344 // performance in some cases. Doh).
346 // The return value is typed primitive, if possible.
348 public object ValidateAttribute (
351 XmlValueGetter attributeValue,
354 if (localName == null)
355 throw new ArgumentNullException ("localName");
357 throw new ArgumentNullException ("ns");
358 if (attributeValue == null)
359 throw new ArgumentNullException ("attributeValue");
361 CheckState (Transition.StartTag);
363 QName qname = new QName (localName, ns);
364 if (occuredAtts.Contains (qname))
365 throw new InvalidOperationException (String.Format ("Attribute '{0}' has already been validated in the same element.", qname));
366 occuredAtts.Add (qname);
368 if (ns == XmlNamespaceManager.XmlnsXmlns)
371 if (schemas.Count == 0)
374 if (Context.Element != null && Context.XsiType == null) {
376 // 3.3.4 Element Locally Valid (Type) - attribute
377 if (Context.ActualType is ComplexType)
378 return AssessAttributeElementLocallyValidType (localName, ns, attributeValue, info);
380 HandleError ("Current simple type cannot accept attributes other than schema instance namespace.");
386 public void ValidateElement (
391 ValidateElement (localName, ns, info, null, null, null, null);
394 public void ValidateElement (
400 string schemaLocation,
401 string noNsSchemaLocation)
403 if (localName == null)
404 throw new ArgumentNullException ("localName");
406 throw new ArgumentNullException ("ns");
408 CheckState (Transition.Content);
409 transition = Transition.StartTag;
411 if (schemaLocation != null)
412 HandleSchemaLocation (schemaLocation);
413 if (noNsSchemaLocation != null)
414 HandleNoNSSchemaLocation (noNsSchemaLocation);
416 elementQNameStack.Add (new XmlQualifiedName (localName, ns));
418 if (schemas.Count == 0)
421 #region ID Constraints
423 idManager.OnStartElement ();
425 defaultAttributes = emptyAttributeArray;
427 // If there is no schema information, then no validation is performed.
428 if (skipValidationDepth < 0 || depth <= skipValidationDepth) {
429 if (shouldValidateCharacters)
430 ValidateEndSimpleContent (null);
432 AssessOpenStartElementSchemaValidity (localName, ns);
436 HandleXsiNil (xsiNil, info);
438 HandleXsiType (xsiType);
440 if (xsiNilDepth < depth)
441 shouldValidateCharacters = true;
444 info.IsNil = xsiNilDepth >= 0;
445 info.SchemaElement = Context.Element;
446 info.SchemaType = Context.ActualSchemaType;
447 info.SchemaAttribute = null;
448 info.IsDefault = false;
449 info.MemberType = null;
450 // FIXME: supply Validity (really useful?)
454 public object ValidateEndElement (XmlSchemaInfo info)
456 return ValidateEndElement (info, null);
459 // The return value is typed primitive, if supplied.
460 // Parameter 'var' seems to be converted into the type
461 // represented by current simple content type. (try passing
462 // some kind of object to this method to check the behavior.)
464 [MonoTODO] // FIXME: Handle 'var' parameter.
465 public object ValidateEndElement (XmlSchemaInfo info,
468 // If it is going to validate an empty element, then
469 // first validate end of attributes.
470 if (transition == Transition.StartTag)
471 ValidateEndOfAttributes (info);
473 CheckState (Transition.Content);
475 elementQNameStack.RemoveAt (elementQNameStack.Count - 1);
477 if (schemas.Count == 0)
480 throw new InvalidOperationException ("There was no corresponding call to 'ValidateElement' method.");
485 if (depth == skipValidationDepth)
486 skipValidationDepth = -1;
487 else if (skipValidationDepth < 0 || depth <= skipValidationDepth)
488 ret = AssessEndElementSchemaValidity (info);
492 // StartTagCloseDeriv
493 // FIXME: fill validity inside this invocation.
494 public void ValidateEndOfAttributes (XmlSchemaInfo info)
497 CheckState (Transition.StartTag);
498 transition = Transition.Content;
499 if (schemas.Count == 0)
502 if (skipValidationDepth < 0 || depth <= skipValidationDepth)
503 AssessCloseStartElementSchemaValidity (info);
506 occuredAtts.Clear ();
510 // LAMESPEC: It should also receive XmlSchemaInfo so that
511 // a validator application can receive simple type or
512 // or content type validation errors.
513 public void ValidateText (string value)
516 throw new ArgumentNullException ("value");
517 ValidateText (delegate () { return value; });
520 // TextDeriv ... without text. Maybe typed check is done by
521 // ValidateAtomicValue().
522 public void ValidateText (XmlValueGetter getter)
525 throw new ArgumentNullException ("getter");
527 CheckState (Transition.Content);
528 if (schemas.Count == 0)
531 if (skipValidationDepth >= 0 && depth > skipValidationDepth)
534 ComplexType ct = Context.ActualType as ComplexType;
536 switch (ct.ContentType) {
537 case XmlSchemaContentType.Empty:
538 HandleError ("Not allowed character content was found.");
540 case XmlSchemaContentType.ElementOnly:
541 string s = storedCharacters.ToString ();
542 if (s.Length > 0 && !XmlChar.IsWhitespace (s))
543 HandleError ("Not allowed character content was found.");
548 ValidateCharacters (getter);
551 public void ValidateWhitespace (string value)
554 throw new ArgumentNullException ("value");
555 ValidateWhitespace (delegate () { return value; });
558 // TextDeriv. It should do the same as ValidateText() in our actual implementation (whitespaces are conditioned).
559 public void ValidateWhitespace (XmlValueGetter getter)
561 ValidateText (getter);
566 #region Error handling
568 private void HandleError (string message)
570 HandleError (message, null, false);
573 private void HandleError (
574 string message, Exception innerException)
576 HandleError (message, innerException, false);
579 private void HandleError (string message,
580 Exception innerException, bool isWarning)
582 if (isWarning && IgnoreWarnings)
585 ValException vex = new ValException (
586 message, nominalEventSender, BaseUri,
587 null, innerException);
588 HandleError (vex, isWarning);
591 private void HandleError (ValException exception)
593 HandleError (exception, false);
596 private void HandleError (ValException exception, bool isWarning)
598 if (isWarning && IgnoreWarnings)
601 if (ValidationEventHandler == null)
604 ValidationEventArgs e = new ValidationEventArgs (
607 isWarning ? XmlSeverityType.Warning :
608 XmlSeverityType.Error);
609 ValidationEventHandler (nominalEventSender, e);
614 private void CheckState (Transition expected)
616 if (transition != expected) {
617 if (transition == Transition.None)
618 throw new InvalidOperationException ("Initialize() must be called before processing validation.");
620 throw new InvalidOperationException (
621 String.Format ("Unexpected attempt to validate state transition from {0} to {1}.",
627 private XsElement FindElement (string name, string ns)
629 return (XsElement) schemas.GlobalElements [new XmlQualifiedName (name, ns)];
632 private XmlSchemaType FindType (XmlQualifiedName qname)
634 return (XmlSchemaType) schemas.GlobalTypes [qname];
637 #region Type Validation
639 private void ValidateStartElementParticle (
640 string localName, string ns)
642 if (Context.State == null)
644 Context.XsiType = null;
645 state.CurrentElement = null;
646 Context.EvaluateStartElement (localName,
648 if (Context.IsInvalid)
649 HandleError ("Invalid start element: " + ns + ":" + localName);
651 Context.PushCurrentElement (state.CurrentElement);
654 private void AssessOpenStartElementSchemaValidity (
655 string localName, string ns)
657 // If the reader is inside xsi:nil (and failed
658 // on validation), then simply skip its content.
659 if (xsiNilDepth >= 0 && xsiNilDepth < depth)
660 HandleError ("Element item appeared, while current element context is nil.");
662 ValidateStartElementParticle (localName, ns);
664 // Create Validation Root, if not exist.
665 // [Schema Validity Assessment (Element) 1.1]
666 if (Context.Element == null) {
667 state.CurrentElement = FindElement (localName, ns);
668 Context.PushCurrentElement (state.CurrentElement);
671 #region Key Constraints
672 if (!IgnoreIdentity) {
673 ValidateKeySelectors ();
674 ValidateKeyFields (false, xsiNilDepth == depth,
675 Context.ActualType, null, null, null);
680 private void AssessCloseStartElementSchemaValidity (XmlSchemaInfo info)
682 if (Context.XsiType != null)
683 AssessCloseStartElementLocallyValidType (info);
684 else if (Context.Element != null) {
685 // element locally valid is checked only when
686 // xsi:type does not exist.
687 AssessElementLocallyValidElement ();
688 if (Context.Element.ElementType != null)
689 AssessCloseStartElementLocallyValidType (info);
692 if (Context.Element == null) {
693 switch (state.ProcessContents) {
694 case ContentProc.Skip:
696 case ContentProc.Lax:
699 QName current = (QName) elementQNameStack [elementQNameStack.Count - 1];
700 if (Context.XsiType == null &&
701 (schemas.Contains (current.Namespace) ||
702 !schemas.MissedSubComponents (current.Namespace)))
703 HandleError ("Element declaration for " + current + " is missing.");
708 // Proceed to the next depth.
710 state.PushContext ();
712 XsdValidationState next = null;
713 if (state.ProcessContents == ContentProc.Skip)
714 skipValidationDepth = depth;
716 // create child particle state.
717 ComplexType xsComplexType = Context.ActualType as ComplexType;
718 if (xsComplexType != null)
719 next = state.Create (xsComplexType.ValidatableParticle);
720 else if (state.ProcessContents == ContentProc.Lax)
721 next = state.Create (XmlSchemaAny.AnyTypeContent);
723 next = state.Create (XmlSchemaParticle.Empty);
725 Context.State = next;
728 // It must be invoked after xsi:nil turned out not to be in
730 private void AssessElementLocallyValidElement ()
732 XsElement element = Context.Element;
733 XmlQualifiedName qname = (XmlQualifiedName) elementQNameStack [elementQNameStack.Count - 1];
736 HandleError ("Element declaration is required for " + qname);
738 if (element.ActualIsAbstract)
739 HandleError ("Abstract element declaration was specified for " + qname);
740 // 3. is checked inside ValidateAttribute().
743 // 3.3.4 Element Locally Valid (Type)
744 private void AssessCloseStartElementLocallyValidType (XmlSchemaInfo info)
746 object schemaType = Context.ActualType;
747 if (schemaType == null) { // 1.
748 HandleError ("Schema type does not exist.");
751 ComplexType cType = schemaType as ComplexType;
752 SimpleType sType = schemaType as SimpleType;
755 // Attributes are checked in ValidateAttribute().
756 } else if (cType != null) {
757 // 3.2. Also, 2. is checked there.
758 AssessCloseStartElementLocallyValidComplexType (cType, info);
762 // 3.4.4 Element Locally Valid (Complex Type)
763 // FIXME: use SchemaInfo for somewhere (? it is passed to ValidateEndOfAttributes() for some reason)
764 private void AssessCloseStartElementLocallyValidComplexType (ComplexType cType, XmlSchemaInfo info)
767 if (cType.IsAbstract) {
768 HandleError ("Target complex type is abstract.");
772 // 2 (xsi:nil and content prohibition)
773 // See AssessStartElementSchemaValidity() and ValidateCharacters()
774 // 3. attribute uses and 5. wild IDs are handled at
775 // ValidateAttribute().
777 // Collect default attributes.
779 foreach (XsAttribute attr in GetExpectedAttributes ()) {
780 if (attr.ValidatedUse == XmlSchemaUse.Required &&
781 attr.ValidatedFixedValue == null)
782 HandleError ("Required attribute " + attr.QualifiedName + " was not found.");
783 else if (attr.ValidatedDefaultValue != null || attr.ValidatedFixedValue != null)
784 defaultAttributesCache.Add (attr);
786 if (defaultAttributesCache.Count == 0)
787 defaultAttributes = emptyAttributeArray;
789 defaultAttributes = (XsAttribute [])
790 defaultAttributesCache.ToArray (
791 typeof (XsAttribute));
792 defaultAttributesCache.Clear ();
793 // 5. wild IDs was already checked at ValidateAttribute().
797 private object AssessAttributeElementLocallyValidType (string localName, string ns, XmlValueGetter getter, XmlSchemaInfo info)
799 ComplexType cType = Context.ActualType as ComplexType;
800 XmlQualifiedName qname = new XmlQualifiedName (localName, ns);
801 // including 3.10.4 Item Valid (Wildcard)
802 XmlSchemaObject attMatch = XmlSchemaUtil.FindAttributeDeclaration (ns, schemas, cType, qname);
803 if (attMatch == null)
804 HandleError ("Attribute declaration was not found for " + qname);
805 XsAttribute attdecl = attMatch as XsAttribute;
806 if (attdecl != null) {
807 AssessAttributeLocallyValidUse (attdecl);
808 return AssessAttributeLocallyValid (attdecl, info, getter);
809 } // otherwise anyAttribute or null.
813 // 3.2.4 Attribute Locally Valid and 3.4.4
814 private object AssessAttributeLocallyValid (XsAttribute attr, XmlSchemaInfo info, XmlValueGetter getter)
817 if (attr.AttributeType == null)
818 HandleError ("Attribute type is missing for " + attr.QualifiedName);
819 XsDatatype dt = attr.AttributeType as XsDatatype;
821 dt = ((SimpleType) attr.AttributeType).Datatype;
823 object parsedValue = null;
825 // It is a bit heavy process, so let's omit as long as possible ;-)
826 if (dt != SimpleType.AnySimpleType || attr.ValidatedFixedValue != null) {
828 CurrentAttributeType = dt;
829 parsedValue = getter ();
830 } catch (Exception ex) { // It is inevitable and bad manner.
831 HandleError (String.Format ("Attribute value is invalid against its data type {0}", dt != null ? dt.TokenizedType : default (XmlTokenizedType)), ex);
834 // check part of 3.14.4 StringValid
835 SimpleType st = attr.AttributeType as SimpleType;
837 ValidateRestrictedSimpleTypeValue (st, ref dt, new XmlAtomicValue (parsedValue, attr.AttributeSchemaType).Value);
839 if (attr.ValidatedFixedValue != null &&
840 !XmlSchemaUtil.AreSchemaDatatypeEqual (
841 attr.AttributeSchemaType, attr.ValidatedFixedTypedValue, attr.AttributeSchemaType, parsedValue)) {
842 HandleError (String.Format ("The value of the attribute {0} does not match with its fixed value '{1}' in the space of type {2}", attr.QualifiedName, attr.ValidatedFixedValue, dt));
843 parsedValue = attr.ValidatedFixedTypedValue;
847 #region ID Constraints
848 if (!IgnoreIdentity) {
849 string error = idManager.AssessEachAttributeIdentityConstraint (dt, parsedValue, ((QName) elementQNameStack [elementQNameStack.Count - 1]).Name);
855 #region Key Constraints
861 attr.QualifiedName.Name,
862 attr.QualifiedName.Namespace,
869 private void AssessAttributeLocallyValidUse (XsAttribute attr)
871 // This is extra check than spec 3.5.4
872 if (attr.ValidatedUse == XmlSchemaUse.Prohibited)
873 HandleError ("Attribute " + attr.QualifiedName + " is prohibited in this context.");
876 private object AssessEndElementSchemaValidity (
879 object ret = ValidateEndSimpleContent (info);
881 ValidateEndElementParticle (); // validate against childrens' state.
883 // 3.3.4 Assess ElementLocallyValidElement 5: value constraints.
884 // 3.3.4 Assess ElementLocallyValidType 3.1.3. = StringValid(3.14.4)
885 // => ValidateEndSimpleContent ().
887 #region Key Constraints
889 ValidateEndElementKeyConstraints ();
892 // Reset xsi:nil, if required.
893 if (xsiNilDepth == depth)
898 private void ValidateEndElementParticle ()
900 if (Context.State != null) {
901 if (!Context.EvaluateEndElement ()) {
902 HandleError ("Invalid end element. There are still required content items.");
905 Context.PopCurrentElement ();
909 // Utility for missing validation completion related to child items.
910 private void ValidateCharacters (XmlValueGetter getter)
912 if (xsiNilDepth >= 0 && xsiNilDepth < depth)
913 HandleError ("Element item appeared, while current element context is nil.");
915 if (shouldValidateCharacters) {
916 CurrentAttributeType = null;
917 storedCharacters.Append (getter ());
922 // Utility for missing validation completion related to child items.
923 private object ValidateEndSimpleContent (XmlSchemaInfo info)
926 if (shouldValidateCharacters)
927 ret = ValidateEndSimpleContentCore (info);
928 shouldValidateCharacters = false;
929 storedCharacters.Length = 0;
933 private object ValidateEndSimpleContentCore (XmlSchemaInfo info)
935 if (Context.ActualType == null)
938 string value = storedCharacters.ToString ();
941 if (value.Length == 0) {
942 // 3.3.4 Element Locally Valid (Element) 5.1.2
943 if (Context.Element != null) {
944 if (Context.Element.ValidatedDefaultValue != null)
945 value = Context.Element.ValidatedDefaultValue;
949 XsDatatype dt = Context.ActualType as XsDatatype;
950 SimpleType st = Context.ActualType as SimpleType;
955 ComplexType ct = Context.ActualType as ComplexType;
957 switch (ct.ContentType) {
958 case XmlSchemaContentType.ElementOnly:
959 if (value.Length > 0 && !XmlChar.IsWhitespace (value))
960 HandleError ("Character content not allowed in an elementOnly model.");
962 case XmlSchemaContentType.Empty:
963 if (value.Length > 0)
964 HandleError ("Character content not allowed in an empty model.");
970 // 3.3.4 Element Locally Valid (Element) :: 5.2.2.2. Fixed value constraints
971 if (Context.Element != null && Context.Element.ValidatedFixedValue != null)
972 if (value != Context.Element.ValidatedFixedValue)
973 HandleError ("Fixed value constraint was not satisfied.");
974 ret = AssessStringValid (st, dt, value);
977 #region Key Constraints
979 ValidateSimpleContentIdentity (dt, value);
982 shouldValidateCharacters = false;
985 info.IsNil = xsiNilDepth >= 0;
986 info.SchemaElement = null;
987 info.SchemaType = Context.ActualType as XmlSchemaType;
988 if (info.SchemaType == null)
989 info.SchemaType = XmlSchemaType.GetBuiltInSimpleType (dt.TypeCode);
990 info.SchemaAttribute = null;
991 info.IsDefault = false; // FIXME: might be true
992 info.MemberType = null; // FIXME: check
993 // FIXME: supply Validity (really useful?)
999 // 3.14.4 String Valid
1000 private object AssessStringValid (SimpleType st,
1001 XsDatatype dt, string value)
1003 XsDatatype validatedDatatype = dt;
1006 string normalized = validatedDatatype.Normalize (value);
1008 XsDatatype itemDatatype;
1009 SimpleType itemSimpleType;
1010 switch (st.DerivedBy) {
1011 case XmlSchemaDerivationMethod.List:
1012 SimpleTypeList listContent = st.Content as SimpleTypeList;
1013 values = normalized.Split (XmlChar.WhitespaceChars);
1014 // LAMESPEC: Types of each element in
1015 // the returned list might be
1016 // inconsistent, so basically returning
1017 // value does not make sense without
1018 // explicit runtime type information
1019 // for base primitive type.
1020 object [] retValues = new object [values.Length];
1021 itemDatatype = listContent.ValidatedListItemType as XsDatatype;
1022 itemSimpleType = listContent.ValidatedListItemType as SimpleType;
1023 for (int vi = 0; vi < values.Length; vi++) {
1024 string each = values [vi];
1025 if (each == String.Empty)
1027 // validate against ValidatedItemType
1028 if (itemDatatype != null) {
1030 retValues [vi] = itemDatatype.ParseValue (each, nameTable, nsResolver);
1031 } catch (Exception ex) { // It is inevitable and bad manner.
1032 HandleError ("List type value contains one or more invalid values.", ex);
1037 AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
1041 case XmlSchemaDerivationMethod.Union:
1042 SimpleTypeUnion union = st.Content as SimpleTypeUnion;
1044 string each = normalized;
1045 // validate against ValidatedItemType
1046 bool passed = false;
1047 foreach (object eachType in union.ValidatedTypes) {
1048 itemDatatype = eachType as XsDatatype;
1049 itemSimpleType = eachType as SimpleType;
1050 if (itemDatatype != null) {
1052 ret = itemDatatype.ParseValue (each, nameTable, nsResolver);
1053 } catch (Exception) { // It is inevitable and bad manner.
1059 ret = AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
1060 } catch (ValException) {
1068 HandleError ("Union type value contains one or more invalid values.");
1073 case XmlSchemaDerivationMethod.Restriction:
1074 SimpleTypeRest str = st.Content as SimpleTypeRest;
1077 /* Don't forget to validate against inherited type's facets
1078 * Could we simplify this by assuming that the basetype will also
1081 // mmm, will check later.
1082 SimpleType baseType = st.BaseXmlSchemaType as SimpleType;
1083 if (baseType != null) {
1084 ret = AssessStringValid (baseType, dt, value);
1086 if (!str.ValidateValueWithFacets (value, nameTable, nsResolver)) {
1087 HandleError ("Specified value was invalid against the facets.");
1091 validatedDatatype = st.Datatype;
1095 if (validatedDatatype != null) {
1097 ret = validatedDatatype.ParseValue (value, nameTable, nsResolver);
1098 } catch (Exception ex) { // It is inevitable and bad manner.
1099 HandleError (String.Format ("Invalidly typed data was specified."), ex);
1105 private void ValidateRestrictedSimpleTypeValue (SimpleType st, ref XsDatatype dt, string normalized)
1109 XsDatatype itemDatatype;
1110 SimpleType itemSimpleType;
1111 switch (st.DerivedBy) {
1112 case XmlSchemaDerivationMethod.List:
1113 SimpleTypeList listContent = st.Content as SimpleTypeList;
1114 values = normalized.Split (XmlChar.WhitespaceChars);
1115 itemDatatype = listContent.ValidatedListItemType as XsDatatype;
1116 itemSimpleType = listContent.ValidatedListItemType as SimpleType;
1117 for (int vi = 0; vi < values.Length; vi++) {
1118 string each = values [vi];
1119 if (each == String.Empty)
1121 // validate against ValidatedItemType
1122 if (itemDatatype != null) {
1124 itemDatatype.ParseValue (each, nameTable, nsResolver);
1125 } catch (Exception ex) { // FIXME: (wishlist) better exception handling ;-(
1126 HandleError ("List type value contains one or more invalid values.", ex);
1131 AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
1134 case XmlSchemaDerivationMethod.Union:
1135 SimpleTypeUnion union = st.Content as SimpleTypeUnion;
1137 string each = normalized;
1138 // validate against ValidatedItemType
1139 bool passed = false;
1140 foreach (object eachType in union.ValidatedTypes) {
1141 itemDatatype = eachType as XsDatatype;
1142 itemSimpleType = eachType as SimpleType;
1143 if (itemDatatype != null) {
1145 itemDatatype.ParseValue (each, nameTable, nsResolver);
1146 } catch (Exception) { // FIXME: (wishlist) better exception handling ;-(
1152 AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
1153 } catch (ValException) {
1161 HandleError ("Union type value contains one or more invalid values.");
1166 case XmlSchemaDerivationMethod.Restriction:
1167 SimpleTypeRest str = st.Content as SimpleTypeRest;
1170 /* Don't forget to validate against inherited type's facets
1171 * Could we simplify this by assuming that the basetype will also
1174 // mmm, will check later.
1175 SimpleType baseType = st.BaseXmlSchemaType as SimpleType;
1176 if (baseType != null) {
1177 AssessStringValid(baseType, dt, normalized);
1179 if (!str.ValidateValueWithFacets (normalized, nameTable, nsResolver)) {
1180 HandleError ("Specified value was invalid against the facets.");
1192 #region Key Constraints Validation
1193 private XsdKeyTable CreateNewKeyTable (XmlSchemaIdentityConstraint ident)
1195 XsdKeyTable seq = new XsdKeyTable (ident);
1196 seq.StartDepth = depth;
1197 this.keyTables.Add (seq);
1201 // 3.11.4 Identity Constraint Satisfied
1202 private void ValidateKeySelectors ()
1204 if (tmpKeyrefPool != null)
1205 tmpKeyrefPool.Clear ();
1206 if (Context.Element != null && Context.Element.Constraints.Count > 0) {
1207 // (a) Create new key sequences, if required.
1208 for (int i = 0; i < Context.Element.Constraints.Count; i++) {
1209 XmlSchemaIdentityConstraint ident = (XmlSchemaIdentityConstraint) Context.Element.Constraints [i];
1210 XsdKeyTable seq = CreateNewKeyTable (ident);
1211 if (ident is XmlSchemaKeyref) {
1212 if (tmpKeyrefPool == null)
1213 tmpKeyrefPool = new ArrayList ();
1214 tmpKeyrefPool.Add (seq);
1219 // (b) Evaluate current key sequences.
1220 for (int i = 0; i < keyTables.Count; i++) {
1221 XsdKeyTable seq = (XsdKeyTable) keyTables [i];
1222 if (seq.SelectorMatches (this.elementQNameStack, depth) != null) {
1223 // creates and registers new entry.
1224 XsdKeyEntry entry = new XsdKeyEntry (seq, depth, lineInfo);
1225 seq.Entries.Add (entry);
1230 private void ValidateKeyFields (bool isAttr, bool isNil, object schemaType, string attrName, string attrNs, XmlValueGetter getter)
1232 // (c) Evaluate field paths.
1233 for (int i = 0; i < keyTables.Count; i++) {
1234 XsdKeyTable seq = (XsdKeyTable) keyTables [i];
1235 // If possible, create new field entry candidates.
1236 for (int j = 0; j < seq.Entries.Count; j++) {
1237 CurrentAttributeType = null;
1239 seq.Entries [j].ProcessMatch (
1248 isAttr ? depth + 1 : depth,
1255 currentKeyFieldConsumers);
1256 } catch (ValException ex) {
1263 private void ValidateEndElementKeyConstraints ()
1265 // Reset Identity constraints.
1266 for (int i = 0; i < keyTables.Count; i++) {
1267 XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
1268 if (seq.StartDepth == depth) {
1269 ValidateEndKeyConstraint (seq);
1271 for (int k = 0; k < seq.Entries.Count; k++) {
1272 XsdKeyEntry entry = seq.Entries [k] as XsdKeyEntry;
1273 // Remove finished (maybe key not found) entries.
1274 if (entry.StartDepth == depth) {
1276 seq.FinishedEntries.Add (entry);
1277 else if (seq.SourceSchemaIdentity is XmlSchemaKey)
1278 HandleError ("Key sequence is missing.");
1279 seq.Entries.RemoveAt (k);
1282 // Pop validated key depth to find two or more fields.
1284 for (int j = 0; j < entry.KeyFields.Count; j++) {
1285 XsdKeyEntryField kf = entry.KeyFields [j];
1286 if (!kf.FieldFound && kf.FieldFoundDepth == depth) {
1287 kf.FieldFoundDepth = 0;
1288 kf.FieldFoundPath = null;
1295 for (int i = 0; i < keyTables.Count; i++) {
1296 XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
1297 if (seq.StartDepth == depth) {
1298 keyTables.RemoveAt (i);
1304 private void ValidateEndKeyConstraint (XsdKeyTable seq)
1306 ArrayList errors = new ArrayList ();
1307 for (int i = 0; i < seq.Entries.Count; i++) {
1308 XsdKeyEntry entry = (XsdKeyEntry) seq.Entries [i];
1311 if (seq.SourceSchemaIdentity is XmlSchemaKey)
1312 errors.Add ("line " + entry.SelectorLineNumber + "position " + entry.SelectorLinePosition);
1314 if (errors.Count > 0)
1315 HandleError ("Invalid identity constraints were found. Key was not found. "
1316 + String.Join (", ", errors.ToArray (typeof (string)) as string []));
1319 // Find reference target
1320 XmlSchemaKeyref xsdKeyref = seq.SourceSchemaIdentity as XmlSchemaKeyref;
1321 if (xsdKeyref != null) {
1322 for (int i = this.keyTables.Count - 1; i >= 0; i--) {
1323 XsdKeyTable target = this.keyTables [i] as XsdKeyTable;
1324 if (target.SourceSchemaIdentity == xsdKeyref.Target) {
1325 seq.ReferencedKey = target;
1326 for (int j = 0; j < seq.FinishedEntries.Count; j++) {
1327 XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [j];
1328 for (int k = 0; k < target.FinishedEntries.Count; k++) {
1329 XsdKeyEntry targetEntry = (XsdKeyEntry) target.FinishedEntries [k];
1330 if (entry.CompareIdentity (targetEntry)) {
1331 entry.KeyRefFound = true;
1338 if (seq.ReferencedKey == null)
1339 HandleError ("Target key was not found.");
1340 for (int i = 0; i < seq.FinishedEntries.Count; i++) {
1341 XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [i];
1342 if (!entry.KeyRefFound)
1343 errors.Add (" line " + entry.SelectorLineNumber + ", position " + entry.SelectorLinePosition);
1345 if (errors.Count > 0)
1346 HandleError ("Invalid identity constraints were found. Referenced key was not found: "
1347 + String.Join (" / ", errors.ToArray (typeof (string)) as string []));
1351 private void ValidateSimpleContentIdentity (
1352 XmlSchemaDatatype dt, string value)
1354 // Identity field value
1355 if (currentKeyFieldConsumers != null) {
1356 while (this.currentKeyFieldConsumers.Count > 0) {
1357 XsdKeyEntryField field = this.currentKeyFieldConsumers [0] as XsdKeyEntryField;
1358 if (field.Identity != null)
1359 HandleError ("Two or more identical field was found. Former value is '" + field.Identity + "' .");
1360 object identity = null; // This means empty value
1363 identity = dt.ParseValue (value, nameTable, nsResolver);
1364 } catch (Exception ex) { // It is inevitable and bad manner.
1365 HandleError ("Identity value is invalid against its data type " + dt.TokenizedType, ex);
1368 if (identity == null)
1371 if (!field.SetIdentityField (identity, depth == xsiNilDepth, dt as XsdAnySimpleType, depth, lineInfo))
1372 HandleError ("Two or more identical key value was found: '" + value + "' .");
1373 this.currentKeyFieldConsumers.RemoveAt (0);
1380 private object GetXsiType (string name)
1382 object xsiType = null;
1383 XmlQualifiedName typeQName =
1384 XmlQualifiedName.Parse (name, nsResolver);
1385 if (typeQName == ComplexType.AnyTypeName)
1386 xsiType = ComplexType.AnyType;
1387 else if (XmlSchemaUtil.IsBuiltInDatatypeName (typeQName))
1388 xsiType = XsDatatype.FromName (typeQName);
1390 xsiType = FindType (typeQName);
1394 private void HandleXsiType (string typename)
1396 XsElement element = Context.Element;
1397 object xsiType = GetXsiType (typename);
1398 if (xsiType == null) {
1399 HandleError ("The instance type was not found: " + typename);
1402 XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
1403 if (xsiSchemaType != null && Context.Element != null) {
1404 XmlSchemaType elemBaseType = element.ElementType as XmlSchemaType;
1405 if (elemBaseType != null && (xsiSchemaType.DerivedBy & elemBaseType.FinalResolved) != 0)
1406 HandleError ("The instance type is prohibited by the type of the context element.");
1407 if (elemBaseType != xsiType && (xsiSchemaType.DerivedBy & element.BlockResolved) != 0)
1408 HandleError ("The instance type is prohibited by the context element.");
1410 ComplexType xsiComplexType = xsiType as ComplexType;
1411 if (xsiComplexType != null && xsiComplexType.IsAbstract)
1412 HandleError ("The instance type is abstract: " + typename);
1414 // If current schema type exists, then this xsi:type must be
1415 // valid extension of that type. See 1.2.1.2.4.
1416 if (element != null) {
1417 AssessLocalTypeDerivationOK (xsiType, element.ElementType, element.BlockResolved);
1419 // See also ValidateEndOfAttributes().
1420 Context.XsiType = xsiType;
1424 // It is common to ElementLocallyValid::4 and SchemaValidityAssessment::1.2.1.2.4
1425 private void AssessLocalTypeDerivationOK (object xsiType, object baseType, XmlSchemaDerivationMethod flag)
1427 XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
1428 ComplexType baseComplexType = baseType as ComplexType;
1429 ComplexType xsiComplexType = xsiSchemaType as ComplexType;
1430 if (xsiType != baseType) {
1431 // Extracted (not extraneous) check for 3.4.6 TypeDerivationOK.
1432 if (baseComplexType != null)
1433 flag |= baseComplexType.BlockResolved;
1434 if (flag == XmlSchemaDerivationMethod.All) {
1435 HandleError ("Prohibited element type substitution.");
1437 } else if (xsiSchemaType != null && (flag & xsiSchemaType.DerivedBy) != 0) {
1438 HandleError ("Prohibited element type substitution.");
1443 if (xsiComplexType != null)
1445 xsiComplexType.ValidateTypeDerivationOK (baseType, null, null);
1446 } catch (ValException ex) {
1450 SimpleType xsiSimpleType = xsiType as SimpleType;
1451 if (xsiSimpleType != null) {
1453 xsiSimpleType.ValidateTypeDerivationOK (baseType, null, null, true);
1454 } catch (ValException ex) {
1458 else if (xsiType is XsDatatype) {
1462 HandleError ("Primitive data type cannot be derived type using xsi:type specification.");
1467 private void HandleXsiNil (string value, XmlSchemaInfo info)
1469 XsElement element = Context.Element;
1470 if (!element.ActualIsNillable) {
1471 HandleError (String.Format ("Current element '{0}' is not nillable and thus does not allow occurence of 'nil' attribute.", Context.Element.QualifiedName));
1474 value = value.Trim (XmlChar.WhitespaceChars);
1476 // Note that 3.2.1 xsi:nil constraints are to be
1477 // validated in AssessElementSchemaValidity() and
1478 // ValidateCharacters().
1479 if (value == "true") {
1480 if (element.ValidatedFixedValue != null)
1481 HandleError ("Schema instance nil was specified, where the element declaration for " + element.QualifiedName + "has fixed value constraints.");
1482 xsiNilDepth = depth;
1488 #region External schema resolution
1490 private XmlSchema ReadExternalSchema (string uri)
1492 Uri absUri = new Uri (SourceUri, uri.Trim (XmlChar.WhitespaceChars));
1493 XmlTextReader xtr = null;
1495 xtr = new XmlTextReader (absUri.ToString (),
1496 (Stream) xmlResolver.GetEntity (
1497 absUri, null, typeof (Stream)),
1499 return XmlSchema.Read (
1500 xtr, ValidationEventHandler);
1507 private void HandleSchemaLocation (string schemaLocation)
1509 if (xmlResolver == null)
1511 XmlSchema schema = null;
1512 bool schemaAdded = false;
1513 string [] tmp = null;
1515 schemaLocation = XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.Token).Datatype.ParseValue (schemaLocation, null, null) as string;
1516 tmp = schemaLocation.Split (XmlChar.WhitespaceChars);
1517 } catch (Exception ex) {
1518 HandleError ("Invalid schemaLocation attribute format.", ex, true);
1519 tmp = new string [0];
1521 if (tmp.Length % 2 != 0)
1522 HandleError ("Invalid schemaLocation attribute format.");
1523 for (int i = 0; i < tmp.Length; i += 2) {
1525 schema = ReadExternalSchema (tmp [i + 1]);
1526 } catch (Exception ex) { // It is inevitable and bad manner.
1527 HandleError ("Could not resolve schema location URI: " + schemaLocation, ex, true);
1530 if (schema.TargetNamespace == null)
1531 schema.TargetNamespace = tmp [i];
1532 else if (schema.TargetNamespace != tmp [i])
1533 HandleError ("Specified schema has different target namespace.");
1535 if (schema != null) {
1536 if (!schemas.Contains (schema.TargetNamespace)) {
1538 schemas.Add (schema);
1546 private void HandleNoNSSchemaLocation (string noNsSchemaLocation)
1548 if (xmlResolver == null)
1550 XmlSchema schema = null;
1551 bool schemaAdded = false;
1554 schema = ReadExternalSchema (noNsSchemaLocation);
1555 } catch (Exception ex) { // It is inevitable and bad manner.
1556 HandleError ("Could not resolve schema location URI: " + noNsSchemaLocation, ex, true);
1558 if (schema != null && schema.TargetNamespace != null)
1559 HandleError ("Specified schema has different target namespace.");
1561 if (schema != null) {
1562 if (!schemas.Contains (schema.TargetNamespace)) {
1564 schemas.Add (schema);