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 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 .IgnoreValidationWarnings) != 0; }
208 private bool IgnoreIdentity {
209 get { return (options & ValidationFlags
210 .IgnoreIdentityConstraints) != 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);
273 public object FindID (string name)
275 // It looks returning the element's local name (string)
276 return idManager.FindID (name);
281 public void AddSchema (XmlSchema schema)
283 schemas.Add (schema);
287 public void Initialize ()
292 public void Initialize (SOMObject startType)
294 this.startType = startType;
295 transition = Transition.Content;
296 state = new XsdParticleStateManager ();
297 if (!schemas.IsCompiled)
301 // It must be called at the end of the validation (to check
302 // identity constraints etc.).
303 public void EndValidation ()
305 CheckState (Transition.Content);
306 transition = Transition.Finished;
308 if (schemas.Count == 0)
312 throw new InvalidOperationException (String.Format ("There are {0} open element(s). ValidateEndElement() must be called for each open element.", depth));
314 // 3.3.4 ElementLocallyValidElement 7 = Root Valid.
315 if (!IgnoreIdentity &&
316 idManager.HasMissingIDReferences ())
317 HandleError ("There are missing ID references: " + idManager.GetMissingIDString ());
320 // I guess it is for validation error recovery
321 [MonoTODO ("Find out how XmlSchemaInfo is used.")]
322 public void SkipToEndElement (XmlSchemaInfo info)
324 CheckState (Transition.Content);
325 if (schemas.Count == 0)
330 // I guess this weird XmlValueGetter is for such case that
331 // value might not be required (and thus it improves
332 // performance in some cases. Doh).
334 // The return value is typed primitive, is possible.
336 public object ValidateAttribute (
339 XmlValueGetter attributeValue,
342 CheckState (Transition.StartTag);
344 QName qname = new QName (localName, ns);
345 if (occuredAtts.Contains (qname))
346 throw new InvalidOperationException (String.Format ("Attribute '{0}' has already been validated in the same element.", qname));
347 occuredAtts.Add (qname);
349 if (ns == XmlNamespaceManager.XmlnsXmlns)
352 if (schemas.Count == 0)
355 // 3.3.4 Element Locally Valid (Type) - attribute
356 if (Context.ActualType is ComplexType)
357 return AssessAttributeElementLocallyValidType (localName, ns, attributeValue, info);
359 HandleError ("Current simple type cannot accept attributes other than schema instance namespace.");
364 public void ValidateElement (
369 ValidateElement (localName, ns, info, null, null, null, null);
372 public void ValidateElement (
378 string schemaLocation,
379 string noNsSchemaLocation)
381 CheckState (Transition.Content);
382 transition = Transition.StartTag;
384 if (schemaLocation != null)
385 HandleSchemaLocation (schemaLocation);
386 if (noNsSchemaLocation != null)
387 HandleNoNSSchemaLocation (noNsSchemaLocation);
389 elementQNameStack.Add (new XmlQualifiedName (localName, ns));
391 if (schemas.Count == 0)
394 #region ID Constraints
396 idManager.OnStartElement ();
398 defaultAttributes = emptyAttributeArray;
400 // If there is no schema information, then no validation is performed.
401 if (skipValidationDepth < 0 || depth <= skipValidationDepth) {
402 if (shouldValidateCharacters)
403 ValidateEndSimpleContent (null);
405 AssessOpenStartElementSchemaValidity (localName, ns);
409 HandleXsiNil (xsiNil, info);
411 HandleXsiType (xsiType);
413 shouldValidateCharacters = true;
416 info.IsNil = xsiNilDepth >= 0;
417 info.SchemaElement = Context.Element;
418 info.SchemaType = Context.ActualSchemaType;
419 info.SchemaAttribute = null;
420 info.IsDefault = false;
421 info.MemberType = null;
422 // FIXME: supply Validity (really useful?)
426 public object ValidateEndElement (XmlSchemaInfo schemaInfo)
428 return ValidateEndElement (schemaInfo, null);
431 // The return value is typed primitive, if supplied.
432 // Parameter 'var' seems to be converted into the type
433 // represented by current simple content type. (try passing
434 // some kind of object to this method to check the behavior.)
436 [MonoTODO ("Handle 'var' parameter.")]
437 public object ValidateEndElement (XmlSchemaInfo schemaInfo,
440 CheckState (Transition.Content);
442 elementQNameStack.RemoveAt (elementQNameStack.Count - 1);
444 if (schemas.Count == 0)
447 throw new InvalidOperationException ("There was no corresponding call to 'ValidateElement' method.");
452 if (depth == skipValidationDepth)
453 skipValidationDepth = -1;
454 else if (skipValidationDepth < 0 || depth <= skipValidationDepth)
455 ret = AssessEndElementSchemaValidity (schemaInfo);
459 // StartTagCloseDeriv
460 public void ValidateEndOfAttributes ()
463 CheckState (Transition.StartTag);
464 transition = Transition.Content;
465 if (schemas.Count == 0)
468 AssessCloseStartElementSchemaValidity ();
470 occuredAtts.Clear ();
474 // TextDeriv ... without text. Maybe typed check is done by
475 // ValidateAtomicValue().
476 public void ValidateText (XmlValueGetter getter)
478 CheckState (Transition.Content);
479 if (schemas.Count == 0)
482 ComplexType ct = Context.ActualType as ComplexType;
483 if (ct != null && storedCharacters.Length > 0) {
484 switch (ct.ContentType) {
485 case XmlSchemaContentType.ElementOnly:
486 case XmlSchemaContentType.Empty:
487 HandleError ("Not allowed character content was found.");
492 ValidateCharacters (getter);
497 public void ValidateWhitespace (XmlValueGetter getter)
499 CheckState (Transition.Content);
500 if (schemas.Count == 0)
503 // throw new NotImplementedException ();
508 #region Error handling
510 private void HandleError (string message)
512 HandleError (message, null, false);
515 private void HandleError (
516 string message, Exception innerException)
518 HandleError (message, innerException, false);
521 private void HandleError (string message,
522 Exception innerException, bool isWarning)
524 if (isWarning && IgnoreWarnings)
527 ValException vex = new ValException (
528 message, nominalEventSender, BaseUri,
529 null, innerException);
530 HandleError (vex, isWarning);
533 private void HandleError (ValException exception)
535 HandleError (exception, false);
538 private void HandleError (ValException exception, bool isWarning)
540 if (isWarning && IgnoreWarnings)
543 if (ValidationEventHandler == null)
546 ValidationEventArgs e = new ValidationEventArgs (
549 isWarning ? XmlSeverityType.Warning :
550 XmlSeverityType.Error);
551 ValidationEventHandler (nominalEventSender, e);
556 private void CheckState (Transition expected)
558 if (transition != expected) {
559 if (transition == Transition.None)
560 throw new InvalidOperationException ("Initialize() must be called before processing validation.");
562 throw new InvalidOperationException (
563 String.Format ("Unexpected attempt to validation state transition from {0} to {1} was happened.",
569 private XsElement FindElement (string name, string ns)
571 return (XsElement) schemas.GlobalElements [new XmlQualifiedName (name, ns)];
574 private XmlSchemaType FindType (XmlQualifiedName qname)
576 return (XmlSchemaType) schemas.GlobalTypes [qname];
579 #region Type Validation
581 private void ValidateStartElementParticle (
582 string localName, string ns)
584 if (Context.State == null)
586 Context.XsiType = null;
587 state.CurrentElement = null;
588 Context.EvaluateStartElement (localName,
590 if (Context.IsInvalid)
591 HandleError ("Invalid start element: " + ns + ":" + localName);
593 Context.SetElement (state.CurrentElement);
596 private void AssessOpenStartElementSchemaValidity (
597 string localName, string ns)
599 // If the reader is inside xsi:nil (and failed
600 // on validation), then simply skip its content.
601 if (xsiNilDepth >= 0 && xsiNilDepth < depth)
602 HandleError ("Element item appeared, while current element context is nil.");
604 ValidateStartElementParticle (localName, ns);
606 // Create Validation Root, if not exist.
607 // [Schema Validity Assessment (Element) 1.1]
608 if (Context.Element == null) {
609 state.CurrentElement = FindElement (localName, ns);
610 Context.SetElement (state.CurrentElement);
613 #region Key Constraints
615 ValidateKeySelectors ();
616 ValidateKeyFields (false, xsiNilDepth == depth,
617 Context.ActualType, null, null, null);
621 private void AssessCloseStartElementSchemaValidity ()
623 if (Context.XsiType != null)
624 AssessCloseStartElementLocallyValidType ();
625 else if (Context.Element != null) {
626 // element locally valid is checked only when
627 // xsi:type does not exist.
628 AssessElementLocallyValidElement ();
629 if (Context.Element.ElementType != null)
630 AssessCloseStartElementLocallyValidType ();
633 if (Context.Element == null) {
634 switch (state.ProcessContents) {
635 case ContentProc.Skip:
637 case ContentProc.Lax:
640 QName current = (QName) elementQNameStack [elementQNameStack.Count - 1];
641 if (Context.XsiType == null &&
642 (schemas.Contains (current.Namespace) ||
643 !schemas.MissedSubComponents (current.Namespace)))
644 HandleError ("Element declaration for " + current + " is missing.");
649 // Proceed to the next depth.
651 state.PushContext ();
653 XsdValidationState next = null;
654 if (state.ProcessContents == ContentProc.Skip)
655 skipValidationDepth = depth;
657 // create child particle state.
658 ComplexType xsComplexType = Context.ActualType as ComplexType;
659 if (xsComplexType != null)
660 next = state.Create (xsComplexType.ValidatableParticle);
661 else if (state.ProcessContents == ContentProc.Lax)
662 next = state.Create (XmlSchemaAny.AnyTypeContent);
664 next = state.Create (XmlSchemaParticle.Empty);
666 Context.State = next;
671 // It must be invoked after xsi:nil turned out not to be in
673 private void AssessElementLocallyValidElement ()
675 XsElement element = Context.Element;
676 XmlQualifiedName qname = (XmlQualifiedName) elementQNameStack [elementQNameStack.Count - 1];
679 HandleError ("Element declaration is required for " + qname);
681 if (element.ActualIsAbstract)
682 HandleError ("Abstract element declaration was specified for " + qname);
683 // 3. is checked inside ValidateAttribute().
686 // 3.3.4 Element Locally Valid (Type)
687 private void AssessCloseStartElementLocallyValidType ()
689 object schemaType = Context.ActualType;
690 if (schemaType == null) { // 1.
691 HandleError ("Schema type does not exist.");
694 ComplexType cType = schemaType as ComplexType;
695 SimpleType sType = schemaType as SimpleType;
698 // Attributes are checked in ValidateAttribute().
699 } else if (cType != null) {
700 // 3.2. Also, 2. is checked there.
701 AssessCloseStartElementLocallyValidComplexType (cType);
705 // 3.4.4 Element Locally Valid (Complex Type)
706 private void AssessCloseStartElementLocallyValidComplexType (ComplexType cType)
709 if (cType.IsAbstract) {
710 HandleError ("Target complex type is abstract.");
714 // 2 (xsi:nil and content prohibition)
715 // See AssessStartElementSchemaValidity() and ValidateCharacters()
716 // 3. attribute uses and 5. wild IDs are handled at
717 // ValidateAttribute().
719 // Collect default attributes.
721 foreach (XsAttribute attr in GetExpectedAttributes ()) {
722 if (attr.ValidatedUse == XmlSchemaUse.Required &&
723 attr.ValidatedFixedValue == null)
724 HandleError ("Required attribute " + attr.QualifiedName + " was not found.");
725 else if (attr.ValidatedDefaultValue != null || attr.ValidatedFixedValue != null)
726 defaultAttributesCache.Add (attr);
728 if (defaultAttributesCache.Count == 0)
729 defaultAttributes = emptyAttributeArray;
731 defaultAttributes = (XsAttribute [])
732 defaultAttributesCache.ToArray (
733 typeof (XsAttribute));
734 defaultAttributesCache.Clear ();
735 // 5. wild IDs was already checked at ValidateAttribute().
739 private object AssessAttributeElementLocallyValidType (string localName, string ns, XmlValueGetter getter, XmlSchemaInfo info)
741 ComplexType cType = Context.ActualType as ComplexType;
742 XmlQualifiedName qname = new XmlQualifiedName (localName, ns);
743 // including 3.10.4 Item Valid (Wildcard)
744 XmlSchemaObject attMatch = XmlSchemaUtil.FindAttributeDeclaration (ns, schemas, cType, qname);
745 if (attMatch == null)
746 HandleError ("Attribute declaration was not found for " + qname);
747 XsAttribute attdecl = attMatch as XsAttribute;
748 if (attdecl != null) {
749 AssessAttributeLocallyValidUse (attdecl);
750 return AssessAttributeLocallyValid (attdecl, getter);
751 } // otherwise anyAttribute or null.
755 // 3.2.4 Attribute Locally Valid and 3.4.4
756 private object AssessAttributeLocallyValid (XsAttribute attr, XmlValueGetter getter)
759 if (attr.AttributeType == null)
760 HandleError ("Attribute type is missing for " + attr.QualifiedName);
761 XsDatatype dt = attr.AttributeType as XsDatatype;
763 dt = ((SimpleType) attr.AttributeType).Datatype;
764 // It is a bit heavy process, so let's omit as long as possible ;-)
765 if (dt != SimpleType.AnySimpleType || attr.ValidatedFixedValue != null) {
766 string normalized = dt.Normalize (getter ());
767 object parsedValue = null;
769 parsedValue = dt.ParseValue (normalized, nameTable, nsResolver);
770 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
771 HandleError ("Attribute value is invalid against its data type " + dt.TokenizedType, ex);
773 if (attr.ValidatedFixedValue != null && attr.ValidatedFixedValue != normalized) {
774 HandleError ("The value of the attribute " + attr.QualifiedName + " does not match with its fixed value.");
775 parsedValue = dt.ParseValue (attr.ValidatedFixedValue, nameTable, nsResolver);
777 #region ID Constraints
778 if (!IgnoreIdentity) {
779 string error = idManager.AssessEachAttributeIdentityConstraint (dt, parsedValue, ((QName) elementQNameStack [elementQNameStack.Count - 1]).Name);
785 #region Key Constraints
791 attr.QualifiedName.Name,
792 attr.QualifiedName.Namespace,
801 private void AssessAttributeLocallyValidUse (XsAttribute attr)
803 // This is extra check than spec 3.5.4
804 if (attr.ValidatedUse == XmlSchemaUse.Prohibited)
805 HandleError ("Attribute " + attr.QualifiedName + " is prohibited in this context.");
808 private object AssessEndElementSchemaValidity (
811 ValidateEndElementParticle (); // validate against childrens' state.
813 object ret = ValidateEndSimpleContent (info);
815 // 3.3.4 Assess ElementLocallyValidElement 5: value constraints.
816 // 3.3.4 Assess ElementLocallyValidType 3.1.3. = StringValid(3.14.4)
817 // => ValidateEndSimpleContent ().
819 #region Key Constraints
821 ValidateEndElementKeyConstraints ();
824 // Reset xsi:nil, if required.
825 if (xsiNilDepth == depth)
830 private void ValidateEndElementParticle ()
832 if (Context.State != null) {
833 if (!Context.EvaluateEndElement ()) {
834 HandleError ("Invalid end element. There are still required content items.");
840 // Utility for missing validation completion related to child items.
841 private void ValidateCharacters (XmlValueGetter getter)
843 if (xsiNilDepth >= 0 && xsiNilDepth < depth)
844 HandleError ("Element item appeared, while current element context is nil.");
846 if (shouldValidateCharacters)
847 storedCharacters.Append (getter ());
851 // Utility for missing validation completion related to child items.
852 private object ValidateEndSimpleContent (XmlSchemaInfo info)
855 if (shouldValidateCharacters)
856 ret = ValidateEndSimpleContentCore (info);
857 shouldValidateCharacters = false;
858 storedCharacters.Length = 0;
862 private object ValidateEndSimpleContentCore (XmlSchemaInfo info)
864 if (Context.ActualType == null)
867 string value = storedCharacters.ToString ();
870 if (value.Length == 0) {
871 // 3.3.4 Element Locally Valid (Element) 5.1.2
872 if (Context.Element != null) {
873 if (Context.Element.ValidatedDefaultValue != null)
874 value = Context.Element.ValidatedDefaultValue;
878 XsDatatype dt = Context.ActualType as XsDatatype;
879 SimpleType st = Context.ActualType as SimpleType;
884 ComplexType ct = Context.ActualType as ComplexType;
886 switch (ct.ContentType) {
887 case XmlSchemaContentType.ElementOnly:
888 case XmlSchemaContentType.Empty:
889 if (value.Length > 0)
890 HandleError ("Character content not allowed.");
896 // 3.3.4 Element Locally Valid (Element) :: 5.2.2.2. Fixed value constraints
897 if (Context.Element != null && Context.Element.ValidatedFixedValue != null)
898 if (value != Context.Element.ValidatedFixedValue)
899 HandleError ("Fixed value constraint was not satisfied.");
900 ret = AssessStringValid (st, dt, value);
903 #region Key Constraints
905 ValidateSimpleContentIdentity (dt, value);
908 shouldValidateCharacters = false;
911 info.IsNil = xsiNilDepth >= 0;
912 info.SchemaElement = null;
913 info.SchemaType = st;
915 info.SchemaType = XmlSchemaType.GetBuiltInSimpleType (dt.TypeCode);
916 info.SchemaAttribute = null;
917 info.IsDefault = false; // FIXME: might be true
918 info.MemberType = null; // FIXME: check
919 // FIXME: supply Validity (really useful?)
925 // 3.14.4 String Valid
926 private object AssessStringValid (SimpleType st,
927 XsDatatype dt, string value)
929 XsDatatype validatedDatatype = dt;
932 string normalized = validatedDatatype.Normalize (value);
934 XsDatatype itemDatatype;
935 SimpleType itemSimpleType;
936 switch (st.DerivedBy) {
937 case XmlSchemaDerivationMethod.List:
938 SimpleTypeList listContent = st.Content as SimpleTypeList;
939 values = normalized.Split (XmlChar.WhitespaceChars);
940 // LAMESPEC: Types of each element in
941 // the returned list might be
942 // inconsistent, so basically returning
943 // value does not make sense without
944 // explicit runtime type information
945 // for base primitive type.
946 object [] retValues = new object [values.Length];
947 itemDatatype = listContent.ValidatedListItemType as XsDatatype;
948 itemSimpleType = listContent.ValidatedListItemType as SimpleType;
949 for (int vi = 0; vi < values.Length; vi++) {
950 string each = values [vi];
951 if (each == String.Empty)
953 // validate against ValidatedItemType
954 if (itemDatatype != null) {
956 retValues [vi] = itemDatatype.ParseValue (each, nameTable, nsResolver);
957 } catch (Exception ex) { // FIXME: (wishlist) better exception handling ;-(
958 HandleError ("List type value contains one or more invalid values.", ex);
963 AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
967 case XmlSchemaDerivationMethod.Union:
968 SimpleTypeUnion union = st.Content as SimpleTypeUnion;
970 string each = normalized;
971 // validate against ValidatedItemType
973 foreach (object eachType in union.ValidatedTypes) {
974 itemDatatype = eachType as XsDatatype;
975 itemSimpleType = eachType as SimpleType;
976 if (itemDatatype != null) {
978 ret = itemDatatype.ParseValue (each, nameTable, nsResolver);
979 } catch (Exception) { // FIXME: (wishlist) better exception handling ;-(
985 ret = AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
986 } catch (ValException) {
994 HandleError ("Union type value contains one or more invalid values.");
999 case XmlSchemaDerivationMethod.Restriction:
1000 SimpleTypeRest str = st.Content as SimpleTypeRest;
1003 /* Don't forget to validate against inherited type's facets
1004 * Could we simplify this by assuming that the basetype will also
1007 // mmm, will check later.
1008 SimpleType baseType = st.BaseXmlSchemaType as SimpleType;
1009 if (baseType != null) {
1010 ret = AssessStringValid (baseType, dt, normalized);
1012 if (!str.ValidateValueWithFacets (normalized, nameTable)) {
1013 HandleError ("Specified value was invalid against the facets.");
1017 validatedDatatype = st.Datatype;
1021 if (validatedDatatype != null) {
1023 ret = validatedDatatype.ParseValue (value, nameTable, nsResolver);
1024 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
1025 HandleError (String.Format ("Invalidly typed data was specified."), ex);
1033 #region Key Constraints Validation
1034 private XsdKeyTable CreateNewKeyTable (XmlSchemaIdentityConstraint ident)
1036 XsdKeyTable seq = new XsdKeyTable (ident);
1037 seq.StartDepth = depth;
1038 this.keyTables.Add (seq);
1042 // 3.11.4 Identity Constraint Satisfied
1043 private void ValidateKeySelectors ()
1045 if (tmpKeyrefPool != null)
1046 tmpKeyrefPool.Clear ();
1047 if (Context.Element != null && Context.Element.Constraints.Count > 0) {
1048 // (a) Create new key sequences, if required.
1049 for (int i = 0; i < Context.Element.Constraints.Count; i++) {
1050 XmlSchemaIdentityConstraint ident = (XmlSchemaIdentityConstraint) Context.Element.Constraints [i];
1051 XsdKeyTable seq = CreateNewKeyTable (ident);
1052 if (ident is XmlSchemaKeyref) {
1053 if (tmpKeyrefPool == null)
1054 tmpKeyrefPool = new ArrayList ();
1055 tmpKeyrefPool.Add (seq);
1060 // (b) Evaluate current key sequences.
1061 for (int i = 0; i < keyTables.Count; i++) {
1062 XsdKeyTable seq = (XsdKeyTable) keyTables [i];
1063 if (seq.SelectorMatches (this.elementQNameStack, depth) != null) {
1064 // creates and registers new entry.
1065 XsdKeyEntry entry = new XsdKeyEntry (seq, depth, lineInfo);
1066 seq.Entries.Add (entry);
1071 private void ValidateKeyFields (bool isAttr, bool isNil, object schemaType, string attrName, string attrNs, XmlValueGetter getter)
1073 // (c) Evaluate field paths.
1074 for (int i = 0; i < keyTables.Count; i++) {
1075 XsdKeyTable seq = (XsdKeyTable) keyTables [i];
1076 // If possible, create new field entry candidates.
1077 for (int j = 0; j < seq.Entries.Count; j++) {
1079 seq.Entries [j].ProcessMatch (
1095 currentKeyFieldConsumers);
1096 } catch (ValException ex) {
1103 private void ProcessKeyEntryOne (XsdKeyEntry entry, bool isAttr, bool isNil, object schemaType, string attrName, string attrNs, XmlValueGetter getter)
1107 private void ValidateEndElementKeyConstraints ()
1109 // Reset Identity constraints.
1110 for (int i = 0; i < keyTables.Count; i++) {
1111 XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
1112 if (seq.StartDepth == depth) {
1113 ValidateEndKeyConstraint (seq);
1115 for (int k = 0; k < seq.Entries.Count; k++) {
1116 XsdKeyEntry entry = seq.Entries [k] as XsdKeyEntry;
1117 // Remove finished (maybe key not found) entries.
1118 if (entry.StartDepth == depth) {
1120 seq.FinishedEntries.Add (entry);
1121 else if (seq.SourceSchemaIdentity is XmlSchemaKey)
1122 HandleError ("Key sequence is missing.");
1123 seq.Entries.RemoveAt (k);
1126 // Pop validated key depth to find two or more fields.
1128 for (int j = 0; j < entry.KeyFields.Count; j++) {
1129 XsdKeyEntryField kf = entry.KeyFields [j];
1130 if (!kf.FieldFound && kf.FieldFoundDepth == depth) {
1131 kf.FieldFoundDepth = 0;
1132 kf.FieldFoundPath = null;
1139 for (int i = 0; i < keyTables.Count; i++) {
1140 XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
1141 if (seq.StartDepth == depth) {
1142 keyTables.RemoveAt (i);
1148 private void ValidateEndKeyConstraint (XsdKeyTable seq)
1150 ArrayList errors = new ArrayList ();
1151 for (int i = 0; i < seq.Entries.Count; i++) {
1152 XsdKeyEntry entry = (XsdKeyEntry) seq.Entries [i];
1155 if (seq.SourceSchemaIdentity is XmlSchemaKey)
1156 errors.Add ("line " + entry.SelectorLineNumber + "position " + entry.SelectorLinePosition);
1158 if (errors.Count > 0)
1159 HandleError ("Invalid identity constraints were found. Key was not found. "
1160 + String.Join (", ", errors.ToArray (typeof (string)) as string []));
1163 // Find reference target
1164 XmlSchemaKeyref xsdKeyref = seq.SourceSchemaIdentity as XmlSchemaKeyref;
1165 if (xsdKeyref != null) {
1166 for (int i = this.keyTables.Count - 1; i >= 0; i--) {
1167 XsdKeyTable target = this.keyTables [i] as XsdKeyTable;
1168 if (target.SourceSchemaIdentity == xsdKeyref.Target) {
1169 seq.ReferencedKey = target;
1170 for (int j = 0; j < seq.FinishedEntries.Count; j++) {
1171 XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [j];
1172 for (int k = 0; k < target.FinishedEntries.Count; k++) {
1173 XsdKeyEntry targetEntry = (XsdKeyEntry) target.FinishedEntries [k];
1174 if (entry.CompareIdentity (targetEntry)) {
1175 entry.KeyRefFound = true;
1182 if (seq.ReferencedKey == null)
1183 HandleError ("Target key was not found.");
1184 for (int i = 0; i < seq.FinishedEntries.Count; i++) {
1185 XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [i];
1186 if (!entry.KeyRefFound)
1187 errors.Add (" line " + entry.SelectorLineNumber + ", position " + entry.SelectorLinePosition);
1189 if (errors.Count > 0)
1190 HandleError ("Invalid identity constraints were found. Referenced key was not found: "
1191 + String.Join (" / ", errors.ToArray (typeof (string)) as string []));
1195 private void ValidateSimpleContentIdentity (
1196 XmlSchemaDatatype dt, string value)
1198 // Identity field value
1199 if (currentKeyFieldConsumers != null) {
1200 while (this.currentKeyFieldConsumers.Count > 0) {
1201 XsdKeyEntryField field = this.currentKeyFieldConsumers [0] as XsdKeyEntryField;
1202 if (field.Identity != null)
1203 HandleError ("Two or more identical field was found. Former value is '" + field.Identity + "' .");
1204 object identity = null; // This means empty value
1207 identity = dt.ParseValue (value, nameTable, nsResolver);
1208 } catch (Exception ex) { // FIXME: (wishlist) This is bad manner ;-(
1209 HandleError ("Identity value is invalid against its data type " + dt.TokenizedType, ex);
1212 if (identity == null)
1215 if (!field.SetIdentityField (identity, depth == xsiNilDepth, dt as XsdAnySimpleType, depth, lineInfo))
1216 HandleError ("Two or more identical key value was found: '" + value + "' .");
1217 this.currentKeyFieldConsumers.RemoveAt (0);
1224 private object GetXsiType (string name)
1226 object xsiType = null;
1227 XmlQualifiedName typeQName =
1228 XmlQualifiedName.Parse (name, nsResolver);
1229 if (typeQName == ComplexType.AnyTypeName)
1230 xsiType = ComplexType.AnyType;
1231 else if (XmlSchemaUtil.IsBuiltInDatatypeName (typeQName))
1232 xsiType = XsDatatype.FromName (typeQName);
1234 xsiType = FindType (typeQName);
1238 private void HandleXsiType (string typename)
1240 XsElement element = Context.Element;
1241 object xsiType = GetXsiType (typename);
1242 if (xsiType == null) {
1243 HandleError ("The instance type was not found: " + typename);
1246 XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
1247 if (xsiSchemaType != null && Context.Element != null) {
1248 XmlSchemaType elemBaseType = element.ElementType as XmlSchemaType;
1249 if (elemBaseType != null && (xsiSchemaType.DerivedBy & elemBaseType.FinalResolved) != 0)
1250 HandleError ("The instance type is prohibited by the type of the context element.");
1251 if (elemBaseType != xsiType && (xsiSchemaType.DerivedBy & element.BlockResolved) != 0)
1252 HandleError ("The instance type is prohibited by the context element.");
1254 ComplexType xsiComplexType = xsiType as ComplexType;
1255 if (xsiComplexType != null && xsiComplexType.IsAbstract)
1256 HandleError ("The instance type is abstract: " + typename);
1258 // If current schema type exists, then this xsi:type must be
1259 // valid extension of that type. See 1.2.1.2.4.
1260 if (element != null) {
1261 AssessLocalTypeDerivationOK (xsiType, element.ElementType, element.BlockResolved);
1263 // See also ValidateEndOfAttributes().
1264 Context.XsiType = xsiType;
1268 // It is common to ElementLocallyValid::4 and SchemaValidityAssessment::1.2.1.2.4
1269 private void AssessLocalTypeDerivationOK (object xsiType, object baseType, XmlSchemaDerivationMethod flag)
1271 XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
1272 ComplexType baseComplexType = baseType as ComplexType;
1273 ComplexType xsiComplexType = xsiSchemaType as ComplexType;
1274 if (xsiType != baseType) {
1275 // Extracted (not extraneous) check for 3.4.6 TypeDerivationOK.
1276 if (baseComplexType != null)
1277 flag |= baseComplexType.BlockResolved;
1278 if (flag == XmlSchemaDerivationMethod.All) {
1279 HandleError ("Prohibited element type substitution.");
1281 } else if (xsiSchemaType != null && (flag & xsiSchemaType.DerivedBy) != 0) {
1282 HandleError ("Prohibited element type substitution.");
1287 if (xsiComplexType != null)
1289 xsiComplexType.ValidateTypeDerivationOK (baseType, null, null);
1290 } catch (ValException ex) {
1294 SimpleType xsiSimpleType = xsiType as SimpleType;
1295 if (xsiSimpleType != null) {
1297 xsiSimpleType.ValidateTypeDerivationOK (baseType, null, null, true);
1298 } catch (ValException ex) {
1302 else if (xsiType is XsDatatype) {
1306 HandleError ("Primitive data type cannot be derived type using xsi:type specification.");
1311 private void HandleXsiNil (string value, XmlSchemaInfo info)
1313 XsElement element = Context.Element;
1314 if (!element.ActualIsNillable) {
1315 HandleError (String.Format ("Current element '{0}' is not nillable and thus does not allow occurence of 'nil' attribute.", Context.Element.QualifiedName));
1318 value = value.Trim (XmlChar.WhitespaceChars);
1320 // Note that 3.2.1 xsi:nil constraints are to be
1321 // validated in AssessElementSchemaValidity() and
1322 // ValidateCharacters().
1323 if (value == "true") {
1324 if (element.ValidatedFixedValue != null)
1325 HandleError ("Schema instance nil was specified, where the element declaration for " + element.QualifiedName + "has fixed value constraints.");
1326 xsiNilDepth = depth;
1332 #region External schema resolution
1334 private XmlSchema ReadExternalSchema (string uri)
1336 Uri absUri = new Uri (SourceUri, uri.Trim (XmlChar.WhitespaceChars));
1337 XmlTextReader xtr = null;
1339 xtr = new XmlTextReader (absUri.ToString (),
1340 (Stream) xmlResolver.GetEntity (
1341 absUri, null, typeof (Stream)),
1343 return XmlSchema.Read (
1344 xtr, ValidationEventHandler);
1351 private void HandleSchemaLocation (string schemaLocation)
1353 if (xmlResolver == null)
1355 XmlSchema schema = null;
1356 bool schemaAdded = false;
1357 string [] tmp = null;
1359 schemaLocation = XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.Token).Datatype.ParseValue (schemaLocation, null, null) as string;
1360 tmp = schemaLocation.Split (XmlChar.WhitespaceChars);
1361 } catch (Exception ex) {
1362 HandleError ("Invalid schemaLocation attribute format.", ex, true);
1363 tmp = new string [0];
1365 if (tmp.Length % 2 != 0)
1366 HandleError ("Invalid schemaLocation attribute format.");
1367 for (int i = 0; i < tmp.Length; i += 2) {
1369 schema = ReadExternalSchema (tmp [i + 1]);
1370 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
1371 HandleError ("Could not resolve schema location URI: " + schemaLocation, ex, true);
1374 if (schema.TargetNamespace == null)
1375 schema.TargetNamespace = tmp [i];
1376 else if (schema.TargetNamespace != tmp [i])
1377 HandleError ("Specified schema has different target namespace.");
1379 if (schema != null) {
1380 if (!schemas.Contains (schema.TargetNamespace)) {
1382 schemas.Add (schema);
1390 private void HandleNoNSSchemaLocation (string noNsSchemaLocation)
1392 if (xmlResolver == null)
1394 XmlSchema schema = null;
1395 bool schemaAdded = false;
1398 schema = ReadExternalSchema (noNsSchemaLocation);
1399 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
1400 HandleError ("Could not resolve schema location URI: " + noNsSchemaLocation, ex, true);
1402 if (schema != null && schema.TargetNamespace != null)
1403 HandleError ("Specified schema has different target namespace.");
1405 if (schema != null) {
1406 if (!schemas.Contains (schema.TargetNamespace)) {
1408 schemas.Add (schema);