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; }
185 public Uri SourceUri {
186 get { return sourceUri; }
187 // FIXME: actually there seems no setter, but then
188 // it will never make sense.
189 set { sourceUri = value; }
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 .ProcessValidationWarnings) == 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 list)
263 if (transition != Transition.StartTag)
264 throw new InvalidOperationException ("Method 'GetUnsoecifiedDefaultAttributes' works only when the validator state is inside a start tag.");
265 foreach (XmlSchemaAttribute attr
266 in GetExpectedAttributes ())
267 if (attr.ValidatedDefaultValue != null || attr.ValidatedFixedValue != null)
270 list.AddRange (defaultAttributes);
275 public void AddSchema (XmlSchema schema)
277 schemas.Add (schema);
281 public void Initialize ()
286 public void Initialize (SOMObject startType)
288 this.startType = startType;
289 transition = Transition.Content;
290 state = new XsdParticleStateManager ();
291 if (!schemas.IsCompiled)
295 // It must be called at the end of the validation (to check
296 // identity constraints etc.).
297 public void EndValidation ()
299 CheckState (Transition.Content);
300 transition = Transition.Finished;
302 if (schemas.Count == 0)
306 throw new InvalidOperationException (String.Format ("There are {0} open element(s). ValidateEndElement() must be called for each open element.", depth));
308 // 3.3.4 ElementLocallyValidElement 7 = Root Valid.
309 if (!IgnoreIdentity &&
310 idManager.HasMissingIDReferences ())
311 HandleError ("There are missing ID references: " + idManager.GetMissingIDString ());
314 // I guess it is for validation error recovery
315 [MonoTODO ("Find out how XmlSchemaInfo is used.")]
316 public void SkipToEndElement (XmlSchemaInfo info)
318 CheckState (Transition.Content);
319 if (schemas.Count == 0)
324 public object ValidateAttribute (
327 string attributeValue,
330 return ValidateAttribute (localName, ns,
331 delegate () { return info.SchemaType.Datatype.ParseValue (attributeValue, nameTable, nsResolver); },
335 // I guess this weird XmlValueGetter is for such case that
336 // value might not be required (and thus it improves
337 // performance in some cases. Doh).
339 // The return value is typed primitive, is possible.
341 public object ValidateAttribute (
344 XmlValueGetter attributeValue,
347 CheckState (Transition.StartTag);
349 QName qname = new QName (localName, ns);
350 if (occuredAtts.Contains (qname))
351 throw new InvalidOperationException (String.Format ("Attribute '{0}' has already been validated in the same element.", qname));
352 occuredAtts.Add (qname);
354 if (ns == XmlNamespaceManager.XmlnsXmlns)
357 if (schemas.Count == 0)
360 // 3.3.4 Element Locally Valid (Type) - attribute
361 if (Context.ActualType is ComplexType)
362 return AssessAttributeElementLocallyValidType (localName, ns, attributeValue, info);
364 HandleError ("Current simple type cannot accept attributes other than schema instance namespace.");
369 public void ValidateElement (
374 ValidateElement (localName, ns, info, null, null, null, null);
377 public void ValidateElement (
383 string schemaLocation,
384 string noNsSchemaLocation)
386 CheckState (Transition.Content);
387 transition = Transition.StartTag;
389 if (schemaLocation != null)
390 HandleSchemaLocation (schemaLocation);
391 if (noNsSchemaLocation != null)
392 HandleNoNSSchemaLocation (noNsSchemaLocation);
394 elementQNameStack.Add (new XmlQualifiedName (localName, ns));
396 if (schemas.Count == 0)
399 #region ID Constraints
401 idManager.OnStartElement ();
403 defaultAttributes = emptyAttributeArray;
405 // If there is no schema information, then no validation is performed.
406 if (skipValidationDepth < 0 || depth <= skipValidationDepth) {
407 if (shouldValidateCharacters)
408 ValidateEndSimpleContent (null);
410 AssessOpenStartElementSchemaValidity (localName, ns);
414 HandleXsiNil (xsiNil, info);
416 HandleXsiType (xsiType);
418 shouldValidateCharacters = true;
421 info.IsNil = xsiNilDepth >= 0;
422 info.SchemaElement = Context.Element;
423 info.SchemaType = Context.ActualSchemaType;
424 info.SchemaAttribute = null;
425 info.IsDefault = false;
426 info.MemberType = null;
427 // FIXME: supply Validity (really useful?)
431 public object ValidateEndElement (XmlSchemaInfo info)
433 return ValidateEndElement (info, null);
436 // The return value is typed primitive, if supplied.
437 // Parameter 'var' seems to be converted into the type
438 // represented by current simple content type. (try passing
439 // some kind of object to this method to check the behavior.)
441 [MonoTODO ("Handle 'var' parameter.")]
442 public object ValidateEndElement (XmlSchemaInfo info,
445 // If it is going to validate an empty element, then
446 // first validate end of attributes.
447 if (transition == Transition.StartTag)
448 ValidateEndOfAttributes (info);
450 CheckState (Transition.Content);
452 elementQNameStack.RemoveAt (elementQNameStack.Count - 1);
454 if (schemas.Count == 0)
457 throw new InvalidOperationException ("There was no corresponding call to 'ValidateElement' method.");
462 if (depth == skipValidationDepth)
463 skipValidationDepth = -1;
464 else if (skipValidationDepth < 0 || depth <= skipValidationDepth)
465 ret = AssessEndElementSchemaValidity (info);
469 // StartTagCloseDeriv
470 // FIXME: fill validity inside this invocation.
471 public void ValidateEndOfAttributes (XmlSchemaInfo info)
474 CheckState (Transition.StartTag);
475 transition = Transition.Content;
476 if (schemas.Count == 0)
479 AssessCloseStartElementSchemaValidity (info);
481 occuredAtts.Clear ();
485 // TextDeriv ... without text. Maybe typed check is done by
486 // ValidateAtomicValue().
487 public void ValidateText (XmlValueGetter getter)
489 CheckState (Transition.Content);
490 if (schemas.Count == 0)
493 ComplexType ct = Context.ActualType as ComplexType;
494 if (ct != null && storedCharacters.Length > 0) {
495 switch (ct.ContentType) {
496 case XmlSchemaContentType.ElementOnly:
497 case XmlSchemaContentType.Empty:
498 HandleError ("Not allowed character content was found.");
503 ValidateCharacters (getter);
508 public void ValidateWhitespace (XmlValueGetter getter)
510 CheckState (Transition.Content);
511 if (schemas.Count == 0)
514 // throw new NotImplementedException ();
519 #region Error handling
521 private void HandleError (string message)
523 HandleError (message, null, false);
526 private void HandleError (
527 string message, Exception innerException)
529 HandleError (message, innerException, false);
532 private void HandleError (string message,
533 Exception innerException, bool isWarning)
535 if (isWarning && IgnoreWarnings)
538 ValException vex = new ValException (
539 message, nominalEventSender, BaseUri,
540 null, innerException);
541 HandleError (vex, isWarning);
544 private void HandleError (ValException exception)
546 HandleError (exception, false);
549 private void HandleError (ValException exception, bool isWarning)
551 if (isWarning && IgnoreWarnings)
554 if (ValidationEventHandler == null)
557 ValidationEventArgs e = new ValidationEventArgs (
560 isWarning ? XmlSeverityType.Warning :
561 XmlSeverityType.Error);
562 ValidationEventHandler (nominalEventSender, e);
567 private void CheckState (Transition expected)
569 if (transition != expected) {
570 if (transition == Transition.None)
571 throw new InvalidOperationException ("Initialize() must be called before processing validation.");
573 throw new InvalidOperationException (
574 String.Format ("Unexpected attempt to validation state transition from {0} to {1} was happened.",
580 private XsElement FindElement (string name, string ns)
582 return (XsElement) schemas.GlobalElements [new XmlQualifiedName (name, ns)];
585 private XmlSchemaType FindType (XmlQualifiedName qname)
587 return (XmlSchemaType) schemas.GlobalTypes [qname];
590 #region Type Validation
592 private void ValidateStartElementParticle (
593 string localName, string ns)
595 if (Context.State == null)
597 Context.XsiType = null;
598 state.CurrentElement = null;
599 Context.EvaluateStartElement (localName,
601 if (Context.IsInvalid)
602 HandleError ("Invalid start element: " + ns + ":" + localName);
604 Context.SetElement (state.CurrentElement);
607 private void AssessOpenStartElementSchemaValidity (
608 string localName, string ns)
610 // If the reader is inside xsi:nil (and failed
611 // on validation), then simply skip its content.
612 if (xsiNilDepth >= 0 && xsiNilDepth < depth)
613 HandleError ("Element item appeared, while current element context is nil.");
615 ValidateStartElementParticle (localName, ns);
617 // Create Validation Root, if not exist.
618 // [Schema Validity Assessment (Element) 1.1]
619 if (Context.Element == null) {
620 state.CurrentElement = FindElement (localName, ns);
621 Context.SetElement (state.CurrentElement);
624 #region Key Constraints
626 ValidateKeySelectors ();
627 ValidateKeyFields (false, xsiNilDepth == depth,
628 Context.ActualType, null, null, null);
632 private void AssessCloseStartElementSchemaValidity (XmlSchemaInfo info)
634 if (Context.XsiType != null)
635 AssessCloseStartElementLocallyValidType (info);
636 else if (Context.Element != null) {
637 // element locally valid is checked only when
638 // xsi:type does not exist.
639 AssessElementLocallyValidElement ();
640 if (Context.Element.ElementType != null)
641 AssessCloseStartElementLocallyValidType (info);
644 if (Context.Element == null) {
645 switch (state.ProcessContents) {
646 case ContentProc.Skip:
648 case ContentProc.Lax:
651 QName current = (QName) elementQNameStack [elementQNameStack.Count - 1];
652 if (Context.XsiType == null &&
653 (schemas.Contains (current.Namespace) ||
654 !schemas.MissedSubComponents (current.Namespace)))
655 HandleError ("Element declaration for " + current + " is missing.");
660 // Proceed to the next depth.
662 state.PushContext ();
664 XsdValidationState next = null;
665 if (state.ProcessContents == ContentProc.Skip)
666 skipValidationDepth = depth;
668 // create child particle state.
669 ComplexType xsComplexType = Context.ActualType as ComplexType;
670 if (xsComplexType != null)
671 next = state.Create (xsComplexType.ValidatableParticle);
672 else if (state.ProcessContents == ContentProc.Lax)
673 next = state.Create (XmlSchemaAny.AnyTypeContent);
675 next = state.Create (XmlSchemaParticle.Empty);
677 Context.State = next;
682 // It must be invoked after xsi:nil turned out not to be in
684 private void AssessElementLocallyValidElement ()
686 XsElement element = Context.Element;
687 XmlQualifiedName qname = (XmlQualifiedName) elementQNameStack [elementQNameStack.Count - 1];
690 HandleError ("Element declaration is required for " + qname);
692 if (element.ActualIsAbstract)
693 HandleError ("Abstract element declaration was specified for " + qname);
694 // 3. is checked inside ValidateAttribute().
697 // 3.3.4 Element Locally Valid (Type)
698 private void AssessCloseStartElementLocallyValidType (XmlSchemaInfo info)
700 object schemaType = Context.ActualType;
701 if (schemaType == null) { // 1.
702 HandleError ("Schema type does not exist.");
705 ComplexType cType = schemaType as ComplexType;
706 SimpleType sType = schemaType as SimpleType;
709 // Attributes are checked in ValidateAttribute().
710 } else if (cType != null) {
711 // 3.2. Also, 2. is checked there.
712 AssessCloseStartElementLocallyValidComplexType (cType, info);
716 // 3.4.4 Element Locally Valid (Complex Type)
717 // FIXME: use SchemaInfo for somewhere (? it is passed to ValidateEndOfAttributes() for some reason)
718 private void AssessCloseStartElementLocallyValidComplexType (ComplexType cType, XmlSchemaInfo info)
721 if (cType.IsAbstract) {
722 HandleError ("Target complex type is abstract.");
726 // 2 (xsi:nil and content prohibition)
727 // See AssessStartElementSchemaValidity() and ValidateCharacters()
728 // 3. attribute uses and 5. wild IDs are handled at
729 // ValidateAttribute().
731 // Collect default attributes.
733 foreach (XsAttribute attr in GetExpectedAttributes ()) {
734 if (attr.ValidatedUse == XmlSchemaUse.Required &&
735 attr.ValidatedFixedValue == null)
736 HandleError ("Required attribute " + attr.QualifiedName + " was not found.");
737 else if (attr.ValidatedDefaultValue != null || attr.ValidatedFixedValue != null)
738 defaultAttributesCache.Add (attr);
740 if (defaultAttributesCache.Count == 0)
741 defaultAttributes = emptyAttributeArray;
743 defaultAttributes = (XsAttribute [])
744 defaultAttributesCache.ToArray (
745 typeof (XsAttribute));
746 defaultAttributesCache.Clear ();
747 // 5. wild IDs was already checked at ValidateAttribute().
751 private object AssessAttributeElementLocallyValidType (string localName, string ns, XmlValueGetter getter, XmlSchemaInfo info)
753 ComplexType cType = Context.ActualType as ComplexType;
754 XmlQualifiedName qname = new XmlQualifiedName (localName, ns);
755 // including 3.10.4 Item Valid (Wildcard)
756 XmlSchemaObject attMatch = XmlSchemaUtil.FindAttributeDeclaration (ns, schemas, cType, qname);
757 if (attMatch == null)
758 HandleError ("Attribute declaration was not found for " + qname);
759 XsAttribute attdecl = attMatch as XsAttribute;
760 if (attdecl != null) {
761 AssessAttributeLocallyValidUse (attdecl);
762 return AssessAttributeLocallyValid (attdecl, info, getter);
763 } // otherwise anyAttribute or null.
767 // 3.2.4 Attribute Locally Valid and 3.4.4
768 private object AssessAttributeLocallyValid (XsAttribute attr, XmlSchemaInfo info, XmlValueGetter getter)
771 if (attr.AttributeType == null)
772 HandleError ("Attribute type is missing for " + attr.QualifiedName);
773 XsDatatype dt = attr.AttributeType as XsDatatype;
775 dt = ((SimpleType) attr.AttributeType).Datatype;
776 // It is a bit heavy process, so let's omit as long as possible ;-)
777 if (dt != SimpleType.AnySimpleType || attr.ValidatedFixedValue != null) {
778 object parsedValue = null;
780 parsedValue = getter ();
781 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
782 HandleError ("Attribute value is invalid against its data type " + dt.TokenizedType, ex);
784 XmlSchemaType type = info != null ? info.SchemaType : null;
785 if (attr.ValidatedFixedValue != null &&
786 !XmlSchemaUtil.IsSchemaDatatypeEquals (
787 attr.AttributeSchemaType.Datatype as XsdAnySimpleType, attr.ValidatedFixedTypedValue, type != null ? type.Datatype as XsdAnySimpleType : null, parsedValue)) {
788 HandleError ("The value of the attribute " + attr.QualifiedName + " does not match with its fixed value.");
789 parsedValue = attr.ValidatedFixedTypedValue;
791 #region ID Constraints
792 if (!IgnoreIdentity) {
793 string error = idManager.AssessEachAttributeIdentityConstraint (dt, parsedValue, ((QName) elementQNameStack [elementQNameStack.Count - 1]).Name);
799 #region Key Constraints
805 attr.QualifiedName.Name,
806 attr.QualifiedName.Namespace,
815 private void AssessAttributeLocallyValidUse (XsAttribute attr)
817 // This is extra check than spec 3.5.4
818 if (attr.ValidatedUse == XmlSchemaUse.Prohibited)
819 HandleError ("Attribute " + attr.QualifiedName + " is prohibited in this context.");
822 private object AssessEndElementSchemaValidity (
825 ValidateEndElementParticle (); // validate against childrens' state.
827 object ret = ValidateEndSimpleContent (info);
829 // 3.3.4 Assess ElementLocallyValidElement 5: value constraints.
830 // 3.3.4 Assess ElementLocallyValidType 3.1.3. = StringValid(3.14.4)
831 // => ValidateEndSimpleContent ().
833 #region Key Constraints
835 ValidateEndElementKeyConstraints ();
838 // Reset xsi:nil, if required.
839 if (xsiNilDepth == depth)
844 private void ValidateEndElementParticle ()
846 if (Context.State != null) {
847 if (!Context.EvaluateEndElement ()) {
848 HandleError ("Invalid end element. There are still required content items.");
854 // Utility for missing validation completion related to child items.
855 private void ValidateCharacters (XmlValueGetter getter)
857 if (xsiNilDepth >= 0 && xsiNilDepth < depth)
858 HandleError ("Element item appeared, while current element context is nil.");
860 if (shouldValidateCharacters)
861 storedCharacters.Append (getter ());
865 // Utility for missing validation completion related to child items.
866 private object ValidateEndSimpleContent (XmlSchemaInfo info)
869 if (shouldValidateCharacters)
870 ret = ValidateEndSimpleContentCore (info);
871 shouldValidateCharacters = false;
872 storedCharacters.Length = 0;
876 private object ValidateEndSimpleContentCore (XmlSchemaInfo info)
878 if (Context.ActualType == null)
881 string value = storedCharacters.ToString ();
884 if (value.Length == 0) {
885 // 3.3.4 Element Locally Valid (Element) 5.1.2
886 if (Context.Element != null) {
887 if (Context.Element.ValidatedDefaultValue != null)
888 value = Context.Element.ValidatedDefaultValue;
892 XsDatatype dt = Context.ActualType as XsDatatype;
893 SimpleType st = Context.ActualType as SimpleType;
898 ComplexType ct = Context.ActualType as ComplexType;
900 switch (ct.ContentType) {
901 case XmlSchemaContentType.ElementOnly:
902 case XmlSchemaContentType.Empty:
903 if (value.Length > 0)
904 HandleError ("Character content not allowed.");
910 // 3.3.4 Element Locally Valid (Element) :: 5.2.2.2. Fixed value constraints
911 if (Context.Element != null && Context.Element.ValidatedFixedValue != null)
912 if (value != Context.Element.ValidatedFixedValue)
913 HandleError ("Fixed value constraint was not satisfied.");
914 ret = AssessStringValid (st, dt, value);
917 #region Key Constraints
919 ValidateSimpleContentIdentity (dt, value);
922 shouldValidateCharacters = false;
925 info.IsNil = xsiNilDepth >= 0;
926 info.SchemaElement = null;
927 info.SchemaType = st;
929 info.SchemaType = XmlSchemaType.GetBuiltInSimpleType (dt.TypeCode);
930 info.SchemaAttribute = null;
931 info.IsDefault = false; // FIXME: might be true
932 info.MemberType = null; // FIXME: check
933 // FIXME: supply Validity (really useful?)
939 // 3.14.4 String Valid
940 private object AssessStringValid (SimpleType st,
941 XsDatatype dt, string value)
943 XsDatatype validatedDatatype = dt;
946 string normalized = validatedDatatype.Normalize (value);
948 XsDatatype itemDatatype;
949 SimpleType itemSimpleType;
950 switch (st.DerivedBy) {
951 case XmlSchemaDerivationMethod.List:
952 SimpleTypeList listContent = st.Content as SimpleTypeList;
953 values = normalized.Split (XmlChar.WhitespaceChars);
954 // LAMESPEC: Types of each element in
955 // the returned list might be
956 // inconsistent, so basically returning
957 // value does not make sense without
958 // explicit runtime type information
959 // for base primitive type.
960 object [] retValues = new object [values.Length];
961 itemDatatype = listContent.ValidatedListItemType as XsDatatype;
962 itemSimpleType = listContent.ValidatedListItemType as SimpleType;
963 for (int vi = 0; vi < values.Length; vi++) {
964 string each = values [vi];
965 if (each == String.Empty)
967 // validate against ValidatedItemType
968 if (itemDatatype != null) {
970 retValues [vi] = itemDatatype.ParseValue (each, nameTable, nsResolver);
971 } catch (Exception ex) { // FIXME: (wishlist) better exception handling ;-(
972 HandleError ("List type value contains one or more invalid values.", ex);
977 AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
981 case XmlSchemaDerivationMethod.Union:
982 SimpleTypeUnion union = st.Content as SimpleTypeUnion;
984 string each = normalized;
985 // validate against ValidatedItemType
987 foreach (object eachType in union.ValidatedTypes) {
988 itemDatatype = eachType as XsDatatype;
989 itemSimpleType = eachType as SimpleType;
990 if (itemDatatype != null) {
992 ret = itemDatatype.ParseValue (each, nameTable, nsResolver);
993 } catch (Exception) { // FIXME: (wishlist) better exception handling ;-(
999 ret = AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
1000 } catch (ValException) {
1008 HandleError ("Union type value contains one or more invalid values.");
1013 case XmlSchemaDerivationMethod.Restriction:
1014 SimpleTypeRest str = st.Content as SimpleTypeRest;
1017 /* Don't forget to validate against inherited type's facets
1018 * Could we simplify this by assuming that the basetype will also
1021 // mmm, will check later.
1022 SimpleType baseType = st.BaseXmlSchemaType as SimpleType;
1023 if (baseType != null) {
1024 ret = AssessStringValid (baseType, dt, normalized);
1026 if (!str.ValidateValueWithFacets (normalized, nameTable)) {
1027 HandleError ("Specified value was invalid against the facets.");
1031 validatedDatatype = st.Datatype;
1035 if (validatedDatatype != null) {
1037 ret = validatedDatatype.ParseValue (value, nameTable, nsResolver);
1038 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
1039 HandleError (String.Format ("Invalidly typed data was specified."), ex);
1047 #region Key Constraints Validation
1048 private XsdKeyTable CreateNewKeyTable (XmlSchemaIdentityConstraint ident)
1050 XsdKeyTable seq = new XsdKeyTable (ident);
1051 seq.StartDepth = depth;
1052 this.keyTables.Add (seq);
1056 // 3.11.4 Identity Constraint Satisfied
1057 private void ValidateKeySelectors ()
1059 if (tmpKeyrefPool != null)
1060 tmpKeyrefPool.Clear ();
1061 if (Context.Element != null && Context.Element.Constraints.Count > 0) {
1062 // (a) Create new key sequences, if required.
1063 for (int i = 0; i < Context.Element.Constraints.Count; i++) {
1064 XmlSchemaIdentityConstraint ident = (XmlSchemaIdentityConstraint) Context.Element.Constraints [i];
1065 XsdKeyTable seq = CreateNewKeyTable (ident);
1066 if (ident is XmlSchemaKeyref) {
1067 if (tmpKeyrefPool == null)
1068 tmpKeyrefPool = new ArrayList ();
1069 tmpKeyrefPool.Add (seq);
1074 // (b) Evaluate current key sequences.
1075 for (int i = 0; i < keyTables.Count; i++) {
1076 XsdKeyTable seq = (XsdKeyTable) keyTables [i];
1077 if (seq.SelectorMatches (this.elementQNameStack, depth) != null) {
1078 // creates and registers new entry.
1079 XsdKeyEntry entry = new XsdKeyEntry (seq, depth, lineInfo);
1080 seq.Entries.Add (entry);
1085 private void ValidateKeyFields (bool isAttr, bool isNil, object schemaType, string attrName, string attrNs, XmlValueGetter getter)
1087 // (c) Evaluate field paths.
1088 for (int i = 0; i < keyTables.Count; i++) {
1089 XsdKeyTable seq = (XsdKeyTable) keyTables [i];
1090 // If possible, create new field entry candidates.
1091 for (int j = 0; j < seq.Entries.Count; j++) {
1093 seq.Entries [j].ProcessMatch (
1109 currentKeyFieldConsumers);
1110 } catch (ValException ex) {
1117 private void ProcessKeyEntryOne (XsdKeyEntry entry, bool isAttr, bool isNil, object schemaType, string attrName, string attrNs, XmlValueGetter getter)
1121 private void ValidateEndElementKeyConstraints ()
1123 // Reset Identity constraints.
1124 for (int i = 0; i < keyTables.Count; i++) {
1125 XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
1126 if (seq.StartDepth == depth) {
1127 ValidateEndKeyConstraint (seq);
1129 for (int k = 0; k < seq.Entries.Count; k++) {
1130 XsdKeyEntry entry = seq.Entries [k] as XsdKeyEntry;
1131 // Remove finished (maybe key not found) entries.
1132 if (entry.StartDepth == depth) {
1134 seq.FinishedEntries.Add (entry);
1135 else if (seq.SourceSchemaIdentity is XmlSchemaKey)
1136 HandleError ("Key sequence is missing.");
1137 seq.Entries.RemoveAt (k);
1140 // Pop validated key depth to find two or more fields.
1142 for (int j = 0; j < entry.KeyFields.Count; j++) {
1143 XsdKeyEntryField kf = entry.KeyFields [j];
1144 if (!kf.FieldFound && kf.FieldFoundDepth == depth) {
1145 kf.FieldFoundDepth = 0;
1146 kf.FieldFoundPath = null;
1153 for (int i = 0; i < keyTables.Count; i++) {
1154 XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
1155 if (seq.StartDepth == depth) {
1156 keyTables.RemoveAt (i);
1162 private void ValidateEndKeyConstraint (XsdKeyTable seq)
1164 ArrayList errors = new ArrayList ();
1165 for (int i = 0; i < seq.Entries.Count; i++) {
1166 XsdKeyEntry entry = (XsdKeyEntry) seq.Entries [i];
1169 if (seq.SourceSchemaIdentity is XmlSchemaKey)
1170 errors.Add ("line " + entry.SelectorLineNumber + "position " + entry.SelectorLinePosition);
1172 if (errors.Count > 0)
1173 HandleError ("Invalid identity constraints were found. Key was not found. "
1174 + String.Join (", ", errors.ToArray (typeof (string)) as string []));
1177 // Find reference target
1178 XmlSchemaKeyref xsdKeyref = seq.SourceSchemaIdentity as XmlSchemaKeyref;
1179 if (xsdKeyref != null) {
1180 for (int i = this.keyTables.Count - 1; i >= 0; i--) {
1181 XsdKeyTable target = this.keyTables [i] as XsdKeyTable;
1182 if (target.SourceSchemaIdentity == xsdKeyref.Target) {
1183 seq.ReferencedKey = target;
1184 for (int j = 0; j < seq.FinishedEntries.Count; j++) {
1185 XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [j];
1186 for (int k = 0; k < target.FinishedEntries.Count; k++) {
1187 XsdKeyEntry targetEntry = (XsdKeyEntry) target.FinishedEntries [k];
1188 if (entry.CompareIdentity (targetEntry)) {
1189 entry.KeyRefFound = true;
1196 if (seq.ReferencedKey == null)
1197 HandleError ("Target key was not found.");
1198 for (int i = 0; i < seq.FinishedEntries.Count; i++) {
1199 XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [i];
1200 if (!entry.KeyRefFound)
1201 errors.Add (" line " + entry.SelectorLineNumber + ", position " + entry.SelectorLinePosition);
1203 if (errors.Count > 0)
1204 HandleError ("Invalid identity constraints were found. Referenced key was not found: "
1205 + String.Join (" / ", errors.ToArray (typeof (string)) as string []));
1209 private void ValidateSimpleContentIdentity (
1210 XmlSchemaDatatype dt, string value)
1212 // Identity field value
1213 if (currentKeyFieldConsumers != null) {
1214 while (this.currentKeyFieldConsumers.Count > 0) {
1215 XsdKeyEntryField field = this.currentKeyFieldConsumers [0] as XsdKeyEntryField;
1216 if (field.Identity != null)
1217 HandleError ("Two or more identical field was found. Former value is '" + field.Identity + "' .");
1218 object identity = null; // This means empty value
1221 identity = dt.ParseValue (value, nameTable, nsResolver);
1222 } catch (Exception ex) { // FIXME: (wishlist) This is bad manner ;-(
1223 HandleError ("Identity value is invalid against its data type " + dt.TokenizedType, ex);
1226 if (identity == null)
1229 if (!field.SetIdentityField (identity, depth == xsiNilDepth, dt as XsdAnySimpleType, depth, lineInfo))
1230 HandleError ("Two or more identical key value was found: '" + value + "' .");
1231 this.currentKeyFieldConsumers.RemoveAt (0);
1238 private object GetXsiType (string name)
1240 object xsiType = null;
1241 XmlQualifiedName typeQName =
1242 XmlQualifiedName.Parse (name, nsResolver);
1243 if (typeQName == ComplexType.AnyTypeName)
1244 xsiType = ComplexType.AnyType;
1245 else if (XmlSchemaUtil.IsBuiltInDatatypeName (typeQName))
1246 xsiType = XsDatatype.FromName (typeQName);
1248 xsiType = FindType (typeQName);
1252 private void HandleXsiType (string typename)
1254 XsElement element = Context.Element;
1255 object xsiType = GetXsiType (typename);
1256 if (xsiType == null) {
1257 HandleError ("The instance type was not found: " + typename);
1260 XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
1261 if (xsiSchemaType != null && Context.Element != null) {
1262 XmlSchemaType elemBaseType = element.ElementType as XmlSchemaType;
1263 if (elemBaseType != null && (xsiSchemaType.DerivedBy & elemBaseType.FinalResolved) != 0)
1264 HandleError ("The instance type is prohibited by the type of the context element.");
1265 if (elemBaseType != xsiType && (xsiSchemaType.DerivedBy & element.BlockResolved) != 0)
1266 HandleError ("The instance type is prohibited by the context element.");
1268 ComplexType xsiComplexType = xsiType as ComplexType;
1269 if (xsiComplexType != null && xsiComplexType.IsAbstract)
1270 HandleError ("The instance type is abstract: " + typename);
1272 // If current schema type exists, then this xsi:type must be
1273 // valid extension of that type. See 1.2.1.2.4.
1274 if (element != null) {
1275 AssessLocalTypeDerivationOK (xsiType, element.ElementType, element.BlockResolved);
1277 // See also ValidateEndOfAttributes().
1278 Context.XsiType = xsiType;
1282 // It is common to ElementLocallyValid::4 and SchemaValidityAssessment::1.2.1.2.4
1283 private void AssessLocalTypeDerivationOK (object xsiType, object baseType, XmlSchemaDerivationMethod flag)
1285 XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
1286 ComplexType baseComplexType = baseType as ComplexType;
1287 ComplexType xsiComplexType = xsiSchemaType as ComplexType;
1288 if (xsiType != baseType) {
1289 // Extracted (not extraneous) check for 3.4.6 TypeDerivationOK.
1290 if (baseComplexType != null)
1291 flag |= baseComplexType.BlockResolved;
1292 if (flag == XmlSchemaDerivationMethod.All) {
1293 HandleError ("Prohibited element type substitution.");
1295 } else if (xsiSchemaType != null && (flag & xsiSchemaType.DerivedBy) != 0) {
1296 HandleError ("Prohibited element type substitution.");
1301 if (xsiComplexType != null)
1303 xsiComplexType.ValidateTypeDerivationOK (baseType, null, null);
1304 } catch (ValException ex) {
1308 SimpleType xsiSimpleType = xsiType as SimpleType;
1309 if (xsiSimpleType != null) {
1311 xsiSimpleType.ValidateTypeDerivationOK (baseType, null, null, true);
1312 } catch (ValException ex) {
1316 else if (xsiType is XsDatatype) {
1320 HandleError ("Primitive data type cannot be derived type using xsi:type specification.");
1325 private void HandleXsiNil (string value, XmlSchemaInfo info)
1327 XsElement element = Context.Element;
1328 if (!element.ActualIsNillable) {
1329 HandleError (String.Format ("Current element '{0}' is not nillable and thus does not allow occurence of 'nil' attribute.", Context.Element.QualifiedName));
1332 value = value.Trim (XmlChar.WhitespaceChars);
1334 // Note that 3.2.1 xsi:nil constraints are to be
1335 // validated in AssessElementSchemaValidity() and
1336 // ValidateCharacters().
1337 if (value == "true") {
1338 if (element.ValidatedFixedValue != null)
1339 HandleError ("Schema instance nil was specified, where the element declaration for " + element.QualifiedName + "has fixed value constraints.");
1340 xsiNilDepth = depth;
1346 #region External schema resolution
1348 private XmlSchema ReadExternalSchema (string uri)
1350 Uri absUri = new Uri (SourceUri, uri.Trim (XmlChar.WhitespaceChars));
1351 XmlTextReader xtr = null;
1353 xtr = new XmlTextReader (absUri.ToString (),
1354 (Stream) xmlResolver.GetEntity (
1355 absUri, null, typeof (Stream)),
1357 return XmlSchema.Read (
1358 xtr, ValidationEventHandler);
1365 private void HandleSchemaLocation (string schemaLocation)
1367 if (xmlResolver == null)
1369 XmlSchema schema = null;
1370 bool schemaAdded = false;
1371 string [] tmp = null;
1373 schemaLocation = XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.Token).Datatype.ParseValue (schemaLocation, null, null) as string;
1374 tmp = schemaLocation.Split (XmlChar.WhitespaceChars);
1375 } catch (Exception ex) {
1376 HandleError ("Invalid schemaLocation attribute format.", ex, true);
1377 tmp = new string [0];
1379 if (tmp.Length % 2 != 0)
1380 HandleError ("Invalid schemaLocation attribute format.");
1381 for (int i = 0; i < tmp.Length; i += 2) {
1383 schema = ReadExternalSchema (tmp [i + 1]);
1384 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
1385 HandleError ("Could not resolve schema location URI: " + schemaLocation, ex, true);
1388 if (schema.TargetNamespace == null)
1389 schema.TargetNamespace = tmp [i];
1390 else if (schema.TargetNamespace != tmp [i])
1391 HandleError ("Specified schema has different target namespace.");
1393 if (schema != null) {
1394 if (!schemas.Contains (schema.TargetNamespace)) {
1396 schemas.Add (schema);
1404 private void HandleNoNSSchemaLocation (string noNsSchemaLocation)
1406 if (xmlResolver == null)
1408 XmlSchema schema = null;
1409 bool schemaAdded = false;
1412 schema = ReadExternalSchema (noNsSchemaLocation);
1413 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
1414 HandleError ("Could not resolve schema location URI: " + noNsSchemaLocation, ex, true);
1416 if (schema != null && schema.TargetNamespace != null)
1417 HandleError ("Specified schema has different target namespace.");
1419 if (schema != null) {
1420 if (!schemas.Contains (schema.TargetNamespace)) {
1422 schemas.Add (schema);