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 .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 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 // LAMESPEC: It should also receive XmlSchemaInfo so that
486 // a validator application can receive simple type or
487 // or content type validation errors.
488 public void ValidateText (string value)
490 ValidateText (delegate () { return value; });
493 // TextDeriv ... without text. Maybe typed check is done by
494 // ValidateAtomicValue().
495 public void ValidateText (XmlValueGetter getter)
497 CheckState (Transition.Content);
498 if (schemas.Count == 0)
501 ComplexType ct = Context.ActualType as ComplexType;
502 if (ct != null && storedCharacters.Length > 0) {
503 switch (ct.ContentType) {
504 case XmlSchemaContentType.ElementOnly:
505 case XmlSchemaContentType.Empty:
506 HandleError ("Not allowed character content was found.");
511 ValidateCharacters (getter);
514 public void ValidateWhitespace (string value)
516 ValidateWhitespace (delegate () { return value; });
521 public void ValidateWhitespace (XmlValueGetter getter)
523 CheckState (Transition.Content);
524 if (schemas.Count == 0)
527 // throw new NotImplementedException ();
532 #region Error handling
534 private void HandleError (string message)
536 HandleError (message, null, false);
539 private void HandleError (
540 string message, Exception innerException)
542 HandleError (message, innerException, false);
545 private void HandleError (string message,
546 Exception innerException, bool isWarning)
548 if (isWarning && IgnoreWarnings)
551 ValException vex = new ValException (
552 message, nominalEventSender, BaseUri,
553 null, innerException);
554 HandleError (vex, isWarning);
557 private void HandleError (ValException exception)
559 HandleError (exception, false);
562 private void HandleError (ValException exception, bool isWarning)
564 if (isWarning && IgnoreWarnings)
567 if (ValidationEventHandler == null)
570 ValidationEventArgs e = new ValidationEventArgs (
573 isWarning ? XmlSeverityType.Warning :
574 XmlSeverityType.Error);
575 ValidationEventHandler (nominalEventSender, e);
580 private void CheckState (Transition expected)
582 if (transition != expected) {
583 if (transition == Transition.None)
584 throw new InvalidOperationException ("Initialize() must be called before processing validation.");
586 throw new InvalidOperationException (
587 String.Format ("Unexpected attempt to validation state transition from {0} to {1} was happened.",
593 private XsElement FindElement (string name, string ns)
595 return (XsElement) schemas.GlobalElements [new XmlQualifiedName (name, ns)];
598 private XmlSchemaType FindType (XmlQualifiedName qname)
600 return (XmlSchemaType) schemas.GlobalTypes [qname];
603 #region Type Validation
605 private void ValidateStartElementParticle (
606 string localName, string ns)
608 if (Context.State == null)
610 Context.XsiType = null;
611 state.CurrentElement = null;
612 Context.EvaluateStartElement (localName,
614 if (Context.IsInvalid)
615 HandleError ("Invalid start element: " + ns + ":" + localName);
617 Context.SetElement (state.CurrentElement);
620 private void AssessOpenStartElementSchemaValidity (
621 string localName, string ns)
623 // If the reader is inside xsi:nil (and failed
624 // on validation), then simply skip its content.
625 if (xsiNilDepth >= 0 && xsiNilDepth < depth)
626 HandleError ("Element item appeared, while current element context is nil.");
628 ValidateStartElementParticle (localName, ns);
630 // Create Validation Root, if not exist.
631 // [Schema Validity Assessment (Element) 1.1]
632 if (Context.Element == null) {
633 state.CurrentElement = FindElement (localName, ns);
634 Context.SetElement (state.CurrentElement);
637 #region Key Constraints
639 ValidateKeySelectors ();
640 ValidateKeyFields (false, xsiNilDepth == depth,
641 Context.ActualType, null, null, null);
645 private void AssessCloseStartElementSchemaValidity (XmlSchemaInfo info)
647 if (Context.XsiType != null)
648 AssessCloseStartElementLocallyValidType (info);
649 else if (Context.Element != null) {
650 // element locally valid is checked only when
651 // xsi:type does not exist.
652 AssessElementLocallyValidElement ();
653 if (Context.Element.ElementType != null)
654 AssessCloseStartElementLocallyValidType (info);
657 if (Context.Element == null) {
658 switch (state.ProcessContents) {
659 case ContentProc.Skip:
661 case ContentProc.Lax:
664 QName current = (QName) elementQNameStack [elementQNameStack.Count - 1];
665 if (Context.XsiType == null &&
666 (schemas.Contains (current.Namespace) ||
667 !schemas.MissedSubComponents (current.Namespace)))
668 HandleError ("Element declaration for " + current + " is missing.");
673 // Proceed to the next depth.
675 state.PushContext ();
677 XsdValidationState next = null;
678 if (state.ProcessContents == ContentProc.Skip)
679 skipValidationDepth = depth;
681 // create child particle state.
682 ComplexType xsComplexType = Context.ActualType as ComplexType;
683 if (xsComplexType != null)
684 next = state.Create (xsComplexType.ValidatableParticle);
685 else if (state.ProcessContents == ContentProc.Lax)
686 next = state.Create (XmlSchemaAny.AnyTypeContent);
688 next = state.Create (XmlSchemaParticle.Empty);
690 Context.State = next;
695 // It must be invoked after xsi:nil turned out not to be in
697 private void AssessElementLocallyValidElement ()
699 XsElement element = Context.Element;
700 XmlQualifiedName qname = (XmlQualifiedName) elementQNameStack [elementQNameStack.Count - 1];
703 HandleError ("Element declaration is required for " + qname);
705 if (element.ActualIsAbstract)
706 HandleError ("Abstract element declaration was specified for " + qname);
707 // 3. is checked inside ValidateAttribute().
710 // 3.3.4 Element Locally Valid (Type)
711 private void AssessCloseStartElementLocallyValidType (XmlSchemaInfo info)
713 object schemaType = Context.ActualType;
714 if (schemaType == null) { // 1.
715 HandleError ("Schema type does not exist.");
718 ComplexType cType = schemaType as ComplexType;
719 SimpleType sType = schemaType as SimpleType;
722 // Attributes are checked in ValidateAttribute().
723 } else if (cType != null) {
724 // 3.2. Also, 2. is checked there.
725 AssessCloseStartElementLocallyValidComplexType (cType, info);
729 // 3.4.4 Element Locally Valid (Complex Type)
730 // FIXME: use SchemaInfo for somewhere (? it is passed to ValidateEndOfAttributes() for some reason)
731 private void AssessCloseStartElementLocallyValidComplexType (ComplexType cType, XmlSchemaInfo info)
734 if (cType.IsAbstract) {
735 HandleError ("Target complex type is abstract.");
739 // 2 (xsi:nil and content prohibition)
740 // See AssessStartElementSchemaValidity() and ValidateCharacters()
741 // 3. attribute uses and 5. wild IDs are handled at
742 // ValidateAttribute().
744 // Collect default attributes.
746 foreach (XsAttribute attr in GetExpectedAttributes ()) {
747 if (attr.ValidatedUse == XmlSchemaUse.Required &&
748 attr.ValidatedFixedValue == null)
749 HandleError ("Required attribute " + attr.QualifiedName + " was not found.");
750 else if (attr.ValidatedDefaultValue != null || attr.ValidatedFixedValue != null)
751 defaultAttributesCache.Add (attr);
753 if (defaultAttributesCache.Count == 0)
754 defaultAttributes = emptyAttributeArray;
756 defaultAttributes = (XsAttribute [])
757 defaultAttributesCache.ToArray (
758 typeof (XsAttribute));
759 defaultAttributesCache.Clear ();
760 // 5. wild IDs was already checked at ValidateAttribute().
764 private object AssessAttributeElementLocallyValidType (string localName, string ns, XmlValueGetter getter, XmlSchemaInfo info)
766 ComplexType cType = Context.ActualType as ComplexType;
767 XmlQualifiedName qname = new XmlQualifiedName (localName, ns);
768 // including 3.10.4 Item Valid (Wildcard)
769 XmlSchemaObject attMatch = XmlSchemaUtil.FindAttributeDeclaration (ns, schemas, cType, qname);
770 if (attMatch == null)
771 HandleError ("Attribute declaration was not found for " + qname);
772 XsAttribute attdecl = attMatch as XsAttribute;
773 if (attdecl != null) {
774 AssessAttributeLocallyValidUse (attdecl);
775 return AssessAttributeLocallyValid (attdecl, info, getter);
776 } // otherwise anyAttribute or null.
780 // 3.2.4 Attribute Locally Valid and 3.4.4
781 private object AssessAttributeLocallyValid (XsAttribute attr, XmlSchemaInfo info, XmlValueGetter getter)
784 if (attr.AttributeType == null)
785 HandleError ("Attribute type is missing for " + attr.QualifiedName);
786 XsDatatype dt = attr.AttributeType as XsDatatype;
788 dt = ((SimpleType) attr.AttributeType).Datatype;
789 // It is a bit heavy process, so let's omit as long as possible ;-)
790 if (dt != SimpleType.AnySimpleType || attr.ValidatedFixedValue != null) {
791 object parsedValue = null;
793 parsedValue = getter ();
794 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
795 HandleError ("Attribute value is invalid against its data type " + dt.TokenizedType, ex);
797 XmlSchemaType type = info != null ? info.SchemaType : null;
798 if (attr.ValidatedFixedValue != null &&
799 !XmlSchemaUtil.IsSchemaDatatypeEquals (
800 attr.AttributeSchemaType.Datatype as XsdAnySimpleType, attr.ValidatedFixedTypedValue, type != null ? type.Datatype as XsdAnySimpleType : null, parsedValue)) {
801 HandleError ("The value of the attribute " + attr.QualifiedName + " does not match with its fixed value.");
802 parsedValue = attr.ValidatedFixedTypedValue;
804 #region ID Constraints
805 if (!IgnoreIdentity) {
806 string error = idManager.AssessEachAttributeIdentityConstraint (dt, parsedValue, ((QName) elementQNameStack [elementQNameStack.Count - 1]).Name);
812 #region Key Constraints
818 attr.QualifiedName.Name,
819 attr.QualifiedName.Namespace,
828 private void AssessAttributeLocallyValidUse (XsAttribute attr)
830 // This is extra check than spec 3.5.4
831 if (attr.ValidatedUse == XmlSchemaUse.Prohibited)
832 HandleError ("Attribute " + attr.QualifiedName + " is prohibited in this context.");
835 private object AssessEndElementSchemaValidity (
838 ValidateEndElementParticle (); // validate against childrens' state.
840 object ret = ValidateEndSimpleContent (info);
842 // 3.3.4 Assess ElementLocallyValidElement 5: value constraints.
843 // 3.3.4 Assess ElementLocallyValidType 3.1.3. = StringValid(3.14.4)
844 // => ValidateEndSimpleContent ().
846 #region Key Constraints
848 ValidateEndElementKeyConstraints ();
851 // Reset xsi:nil, if required.
852 if (xsiNilDepth == depth)
857 private void ValidateEndElementParticle ()
859 if (Context.State != null) {
860 if (!Context.EvaluateEndElement ()) {
861 HandleError ("Invalid end element. There are still required content items.");
867 // Utility for missing validation completion related to child items.
868 private void ValidateCharacters (XmlValueGetter getter)
870 if (xsiNilDepth >= 0 && xsiNilDepth < depth)
871 HandleError ("Element item appeared, while current element context is nil.");
873 if (shouldValidateCharacters)
874 storedCharacters.Append (getter ());
878 // Utility for missing validation completion related to child items.
879 private object ValidateEndSimpleContent (XmlSchemaInfo info)
882 if (shouldValidateCharacters)
883 ret = ValidateEndSimpleContentCore (info);
884 shouldValidateCharacters = false;
885 storedCharacters.Length = 0;
889 private object ValidateEndSimpleContentCore (XmlSchemaInfo info)
891 if (Context.ActualType == null)
894 string value = storedCharacters.ToString ();
897 if (value.Length == 0) {
898 // 3.3.4 Element Locally Valid (Element) 5.1.2
899 if (Context.Element != null) {
900 if (Context.Element.ValidatedDefaultValue != null)
901 value = Context.Element.ValidatedDefaultValue;
905 XsDatatype dt = Context.ActualType as XsDatatype;
906 SimpleType st = Context.ActualType as SimpleType;
911 ComplexType ct = Context.ActualType as ComplexType;
913 switch (ct.ContentType) {
914 case XmlSchemaContentType.ElementOnly:
915 case XmlSchemaContentType.Empty:
916 if (value.Length > 0)
917 HandleError ("Character content not allowed.");
923 // 3.3.4 Element Locally Valid (Element) :: 5.2.2.2. Fixed value constraints
924 if (Context.Element != null && Context.Element.ValidatedFixedValue != null)
925 if (value != Context.Element.ValidatedFixedValue)
926 HandleError ("Fixed value constraint was not satisfied.");
927 ret = AssessStringValid (st, dt, value);
930 #region Key Constraints
932 ValidateSimpleContentIdentity (dt, value);
935 shouldValidateCharacters = false;
938 info.IsNil = xsiNilDepth >= 0;
939 info.SchemaElement = null;
940 info.SchemaType = st;
942 info.SchemaType = XmlSchemaType.GetBuiltInSimpleType (dt.TypeCode);
943 info.SchemaAttribute = null;
944 info.IsDefault = false; // FIXME: might be true
945 info.MemberType = null; // FIXME: check
946 // FIXME: supply Validity (really useful?)
952 // 3.14.4 String Valid
953 private object AssessStringValid (SimpleType st,
954 XsDatatype dt, string value)
956 XsDatatype validatedDatatype = dt;
959 string normalized = validatedDatatype.Normalize (value);
961 XsDatatype itemDatatype;
962 SimpleType itemSimpleType;
963 switch (st.DerivedBy) {
964 case XmlSchemaDerivationMethod.List:
965 SimpleTypeList listContent = st.Content as SimpleTypeList;
966 values = normalized.Split (XmlChar.WhitespaceChars);
967 // LAMESPEC: Types of each element in
968 // the returned list might be
969 // inconsistent, so basically returning
970 // value does not make sense without
971 // explicit runtime type information
972 // for base primitive type.
973 object [] retValues = new object [values.Length];
974 itemDatatype = listContent.ValidatedListItemType as XsDatatype;
975 itemSimpleType = listContent.ValidatedListItemType as SimpleType;
976 for (int vi = 0; vi < values.Length; vi++) {
977 string each = values [vi];
978 if (each == String.Empty)
980 // validate against ValidatedItemType
981 if (itemDatatype != null) {
983 retValues [vi] = itemDatatype.ParseValue (each, nameTable, nsResolver);
984 } catch (Exception ex) { // FIXME: (wishlist) better exception handling ;-(
985 HandleError ("List type value contains one or more invalid values.", ex);
990 AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
994 case XmlSchemaDerivationMethod.Union:
995 SimpleTypeUnion union = st.Content as SimpleTypeUnion;
997 string each = normalized;
998 // validate against ValidatedItemType
1000 foreach (object eachType in union.ValidatedTypes) {
1001 itemDatatype = eachType as XsDatatype;
1002 itemSimpleType = eachType as SimpleType;
1003 if (itemDatatype != null) {
1005 ret = itemDatatype.ParseValue (each, nameTable, nsResolver);
1006 } catch (Exception) { // FIXME: (wishlist) better exception handling ;-(
1012 ret = AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
1013 } catch (ValException) {
1021 HandleError ("Union type value contains one or more invalid values.");
1026 case XmlSchemaDerivationMethod.Restriction:
1027 SimpleTypeRest str = st.Content as SimpleTypeRest;
1030 /* Don't forget to validate against inherited type's facets
1031 * Could we simplify this by assuming that the basetype will also
1034 // mmm, will check later.
1035 SimpleType baseType = st.BaseXmlSchemaType as SimpleType;
1036 if (baseType != null) {
1037 ret = AssessStringValid (baseType, dt, normalized);
1039 if (!str.ValidateValueWithFacets (normalized, nameTable)) {
1040 HandleError ("Specified value was invalid against the facets.");
1044 validatedDatatype = st.Datatype;
1048 if (validatedDatatype != null) {
1050 ret = validatedDatatype.ParseValue (value, nameTable, nsResolver);
1051 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
1052 HandleError (String.Format ("Invalidly typed data was specified."), ex);
1060 #region Key Constraints Validation
1061 private XsdKeyTable CreateNewKeyTable (XmlSchemaIdentityConstraint ident)
1063 XsdKeyTable seq = new XsdKeyTable (ident);
1064 seq.StartDepth = depth;
1065 this.keyTables.Add (seq);
1069 // 3.11.4 Identity Constraint Satisfied
1070 private void ValidateKeySelectors ()
1072 if (tmpKeyrefPool != null)
1073 tmpKeyrefPool.Clear ();
1074 if (Context.Element != null && Context.Element.Constraints.Count > 0) {
1075 // (a) Create new key sequences, if required.
1076 for (int i = 0; i < Context.Element.Constraints.Count; i++) {
1077 XmlSchemaIdentityConstraint ident = (XmlSchemaIdentityConstraint) Context.Element.Constraints [i];
1078 XsdKeyTable seq = CreateNewKeyTable (ident);
1079 if (ident is XmlSchemaKeyref) {
1080 if (tmpKeyrefPool == null)
1081 tmpKeyrefPool = new ArrayList ();
1082 tmpKeyrefPool.Add (seq);
1087 // (b) Evaluate current key sequences.
1088 for (int i = 0; i < keyTables.Count; i++) {
1089 XsdKeyTable seq = (XsdKeyTable) keyTables [i];
1090 if (seq.SelectorMatches (this.elementQNameStack, depth) != null) {
1091 // creates and registers new entry.
1092 XsdKeyEntry entry = new XsdKeyEntry (seq, depth, lineInfo);
1093 seq.Entries.Add (entry);
1098 private void ValidateKeyFields (bool isAttr, bool isNil, object schemaType, string attrName, string attrNs, XmlValueGetter getter)
1100 // (c) Evaluate field paths.
1101 for (int i = 0; i < keyTables.Count; i++) {
1102 XsdKeyTable seq = (XsdKeyTable) keyTables [i];
1103 // If possible, create new field entry candidates.
1104 for (int j = 0; j < seq.Entries.Count; j++) {
1106 seq.Entries [j].ProcessMatch (
1122 currentKeyFieldConsumers);
1123 } catch (ValException ex) {
1130 private void ProcessKeyEntryOne (XsdKeyEntry entry, bool isAttr, bool isNil, object schemaType, string attrName, string attrNs, XmlValueGetter getter)
1134 private void ValidateEndElementKeyConstraints ()
1136 // Reset Identity constraints.
1137 for (int i = 0; i < keyTables.Count; i++) {
1138 XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
1139 if (seq.StartDepth == depth) {
1140 ValidateEndKeyConstraint (seq);
1142 for (int k = 0; k < seq.Entries.Count; k++) {
1143 XsdKeyEntry entry = seq.Entries [k] as XsdKeyEntry;
1144 // Remove finished (maybe key not found) entries.
1145 if (entry.StartDepth == depth) {
1147 seq.FinishedEntries.Add (entry);
1148 else if (seq.SourceSchemaIdentity is XmlSchemaKey)
1149 HandleError ("Key sequence is missing.");
1150 seq.Entries.RemoveAt (k);
1153 // Pop validated key depth to find two or more fields.
1155 for (int j = 0; j < entry.KeyFields.Count; j++) {
1156 XsdKeyEntryField kf = entry.KeyFields [j];
1157 if (!kf.FieldFound && kf.FieldFoundDepth == depth) {
1158 kf.FieldFoundDepth = 0;
1159 kf.FieldFoundPath = null;
1166 for (int i = 0; i < keyTables.Count; i++) {
1167 XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
1168 if (seq.StartDepth == depth) {
1169 keyTables.RemoveAt (i);
1175 private void ValidateEndKeyConstraint (XsdKeyTable seq)
1177 ArrayList errors = new ArrayList ();
1178 for (int i = 0; i < seq.Entries.Count; i++) {
1179 XsdKeyEntry entry = (XsdKeyEntry) seq.Entries [i];
1182 if (seq.SourceSchemaIdentity is XmlSchemaKey)
1183 errors.Add ("line " + entry.SelectorLineNumber + "position " + entry.SelectorLinePosition);
1185 if (errors.Count > 0)
1186 HandleError ("Invalid identity constraints were found. Key was not found. "
1187 + String.Join (", ", errors.ToArray (typeof (string)) as string []));
1190 // Find reference target
1191 XmlSchemaKeyref xsdKeyref = seq.SourceSchemaIdentity as XmlSchemaKeyref;
1192 if (xsdKeyref != null) {
1193 for (int i = this.keyTables.Count - 1; i >= 0; i--) {
1194 XsdKeyTable target = this.keyTables [i] as XsdKeyTable;
1195 if (target.SourceSchemaIdentity == xsdKeyref.Target) {
1196 seq.ReferencedKey = target;
1197 for (int j = 0; j < seq.FinishedEntries.Count; j++) {
1198 XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [j];
1199 for (int k = 0; k < target.FinishedEntries.Count; k++) {
1200 XsdKeyEntry targetEntry = (XsdKeyEntry) target.FinishedEntries [k];
1201 if (entry.CompareIdentity (targetEntry)) {
1202 entry.KeyRefFound = true;
1209 if (seq.ReferencedKey == null)
1210 HandleError ("Target key was not found.");
1211 for (int i = 0; i < seq.FinishedEntries.Count; i++) {
1212 XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [i];
1213 if (!entry.KeyRefFound)
1214 errors.Add (" line " + entry.SelectorLineNumber + ", position " + entry.SelectorLinePosition);
1216 if (errors.Count > 0)
1217 HandleError ("Invalid identity constraints were found. Referenced key was not found: "
1218 + String.Join (" / ", errors.ToArray (typeof (string)) as string []));
1222 private void ValidateSimpleContentIdentity (
1223 XmlSchemaDatatype dt, string value)
1225 // Identity field value
1226 if (currentKeyFieldConsumers != null) {
1227 while (this.currentKeyFieldConsumers.Count > 0) {
1228 XsdKeyEntryField field = this.currentKeyFieldConsumers [0] as XsdKeyEntryField;
1229 if (field.Identity != null)
1230 HandleError ("Two or more identical field was found. Former value is '" + field.Identity + "' .");
1231 object identity = null; // This means empty value
1234 identity = dt.ParseValue (value, nameTable, nsResolver);
1235 } catch (Exception ex) { // FIXME: (wishlist) This is bad manner ;-(
1236 HandleError ("Identity value is invalid against its data type " + dt.TokenizedType, ex);
1239 if (identity == null)
1242 if (!field.SetIdentityField (identity, depth == xsiNilDepth, dt as XsdAnySimpleType, depth, lineInfo))
1243 HandleError ("Two or more identical key value was found: '" + value + "' .");
1244 this.currentKeyFieldConsumers.RemoveAt (0);
1251 private object GetXsiType (string name)
1253 object xsiType = null;
1254 XmlQualifiedName typeQName =
1255 XmlQualifiedName.Parse (name, nsResolver);
1256 if (typeQName == ComplexType.AnyTypeName)
1257 xsiType = ComplexType.AnyType;
1258 else if (XmlSchemaUtil.IsBuiltInDatatypeName (typeQName))
1259 xsiType = XsDatatype.FromName (typeQName);
1261 xsiType = FindType (typeQName);
1265 private void HandleXsiType (string typename)
1267 XsElement element = Context.Element;
1268 object xsiType = GetXsiType (typename);
1269 if (xsiType == null) {
1270 HandleError ("The instance type was not found: " + typename);
1273 XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
1274 if (xsiSchemaType != null && Context.Element != null) {
1275 XmlSchemaType elemBaseType = element.ElementType as XmlSchemaType;
1276 if (elemBaseType != null && (xsiSchemaType.DerivedBy & elemBaseType.FinalResolved) != 0)
1277 HandleError ("The instance type is prohibited by the type of the context element.");
1278 if (elemBaseType != xsiType && (xsiSchemaType.DerivedBy & element.BlockResolved) != 0)
1279 HandleError ("The instance type is prohibited by the context element.");
1281 ComplexType xsiComplexType = xsiType as ComplexType;
1282 if (xsiComplexType != null && xsiComplexType.IsAbstract)
1283 HandleError ("The instance type is abstract: " + typename);
1285 // If current schema type exists, then this xsi:type must be
1286 // valid extension of that type. See 1.2.1.2.4.
1287 if (element != null) {
1288 AssessLocalTypeDerivationOK (xsiType, element.ElementType, element.BlockResolved);
1290 // See also ValidateEndOfAttributes().
1291 Context.XsiType = xsiType;
1295 // It is common to ElementLocallyValid::4 and SchemaValidityAssessment::1.2.1.2.4
1296 private void AssessLocalTypeDerivationOK (object xsiType, object baseType, XmlSchemaDerivationMethod flag)
1298 XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
1299 ComplexType baseComplexType = baseType as ComplexType;
1300 ComplexType xsiComplexType = xsiSchemaType as ComplexType;
1301 if (xsiType != baseType) {
1302 // Extracted (not extraneous) check for 3.4.6 TypeDerivationOK.
1303 if (baseComplexType != null)
1304 flag |= baseComplexType.BlockResolved;
1305 if (flag == XmlSchemaDerivationMethod.All) {
1306 HandleError ("Prohibited element type substitution.");
1308 } else if (xsiSchemaType != null && (flag & xsiSchemaType.DerivedBy) != 0) {
1309 HandleError ("Prohibited element type substitution.");
1314 if (xsiComplexType != null)
1316 xsiComplexType.ValidateTypeDerivationOK (baseType, null, null);
1317 } catch (ValException ex) {
1321 SimpleType xsiSimpleType = xsiType as SimpleType;
1322 if (xsiSimpleType != null) {
1324 xsiSimpleType.ValidateTypeDerivationOK (baseType, null, null, true);
1325 } catch (ValException ex) {
1329 else if (xsiType is XsDatatype) {
1333 HandleError ("Primitive data type cannot be derived type using xsi:type specification.");
1338 private void HandleXsiNil (string value, XmlSchemaInfo info)
1340 XsElement element = Context.Element;
1341 if (!element.ActualIsNillable) {
1342 HandleError (String.Format ("Current element '{0}' is not nillable and thus does not allow occurence of 'nil' attribute.", Context.Element.QualifiedName));
1345 value = value.Trim (XmlChar.WhitespaceChars);
1347 // Note that 3.2.1 xsi:nil constraints are to be
1348 // validated in AssessElementSchemaValidity() and
1349 // ValidateCharacters().
1350 if (value == "true") {
1351 if (element.ValidatedFixedValue != null)
1352 HandleError ("Schema instance nil was specified, where the element declaration for " + element.QualifiedName + "has fixed value constraints.");
1353 xsiNilDepth = depth;
1359 #region External schema resolution
1361 private XmlSchema ReadExternalSchema (string uri)
1363 Uri absUri = new Uri (SourceUri, uri.Trim (XmlChar.WhitespaceChars));
1364 XmlTextReader xtr = null;
1366 xtr = new XmlTextReader (absUri.ToString (),
1367 (Stream) xmlResolver.GetEntity (
1368 absUri, null, typeof (Stream)),
1370 return XmlSchema.Read (
1371 xtr, ValidationEventHandler);
1378 private void HandleSchemaLocation (string schemaLocation)
1380 if (xmlResolver == null)
1382 XmlSchema schema = null;
1383 bool schemaAdded = false;
1384 string [] tmp = null;
1386 schemaLocation = XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.Token).Datatype.ParseValue (schemaLocation, null, null) as string;
1387 tmp = schemaLocation.Split (XmlChar.WhitespaceChars);
1388 } catch (Exception ex) {
1389 HandleError ("Invalid schemaLocation attribute format.", ex, true);
1390 tmp = new string [0];
1392 if (tmp.Length % 2 != 0)
1393 HandleError ("Invalid schemaLocation attribute format.");
1394 for (int i = 0; i < tmp.Length; i += 2) {
1396 schema = ReadExternalSchema (tmp [i + 1]);
1397 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
1398 HandleError ("Could not resolve schema location URI: " + schemaLocation, ex, true);
1401 if (schema.TargetNamespace == null)
1402 schema.TargetNamespace = tmp [i];
1403 else if (schema.TargetNamespace != tmp [i])
1404 HandleError ("Specified schema has different target namespace.");
1406 if (schema != null) {
1407 if (!schemas.Contains (schema.TargetNamespace)) {
1409 schemas.Add (schema);
1417 private void HandleNoNSSchemaLocation (string noNsSchemaLocation)
1419 if (xmlResolver == null)
1421 XmlSchema schema = null;
1422 bool schemaAdded = false;
1425 schema = ReadExternalSchema (noNsSchemaLocation);
1426 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
1427 HandleError ("Could not resolve schema location URI: " + noNsSchemaLocation, ex, true);
1429 if (schema != null && schema.TargetNamespace != null)
1430 HandleError ("Specified schema has different target namespace.");
1432 if (schema != null) {
1433 if (!schemas.Contains (schema.TargetNamespace)) {
1435 schemas.Add (schema);