2 // XmlSchemaValidator.cs
5 // Atsushi Enomoto <atsushi@ximian.com>
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 // - There is no assurance that xsi:type precedes to any other attributes,
34 // or xsi:type is not handled.
35 // - There is no SourceUri provision.
41 using System
.Collections
;
45 using Mono
.Xml
.Schema
;
47 using QName
= System
.Xml
.XmlQualifiedName
;
48 using Form
= System
.Xml
.Schema
.XmlSchemaForm
;
49 using Use
= System
.Xml
.Schema
.XmlSchemaUse
;
50 using ContentType
= System
.Xml
.Schema
.XmlSchemaContentType
;
51 using Validity
= System
.Xml
.Schema
.XmlSchemaValidity
;
52 using ValidationFlags
= System
.Xml
.Schema
.XmlSchemaValidationFlags
;
53 using ContentProc
= System
.Xml
.Schema
.XmlSchemaContentProcessing
;
54 using SOMList
= System
.Xml
.Schema
.XmlSchemaObjectCollection
;
55 using SOMObject
= System
.Xml
.Schema
.XmlSchemaObject
;
56 using XsElement
= System
.Xml
.Schema
.XmlSchemaElement
;
57 using XsAttribute
= System
.Xml
.Schema
.XmlSchemaAttribute
;
58 using AttrGroup
= System
.Xml
.Schema
.XmlSchemaAttributeGroup
;
59 using AttrGroupRef
= System
.Xml
.Schema
.XmlSchemaAttributeGroupRef
;
60 using XsDatatype
= System
.Xml
.Schema
.XmlSchemaDatatype
;
61 using SimpleType
= System
.Xml
.Schema
.XmlSchemaSimpleType
;
62 using ComplexType
= System
.Xml
.Schema
.XmlSchemaComplexType
;
63 using SimpleModel
= System
.Xml
.Schema
.XmlSchemaSimpleContent
;
64 using SimpleExt
= System
.Xml
.Schema
.XmlSchemaSimpleContentExtension
;
65 using SimpleRst
= System
.Xml
.Schema
.XmlSchemaSimpleContentRestriction
;
66 using ComplexModel
= System
.Xml
.Schema
.XmlSchemaComplexContent
;
67 using ComplexExt
= System
.Xml
.Schema
.XmlSchemaComplexContentExtension
;
68 using ComplexRst
= System
.Xml
.Schema
.XmlSchemaComplexContentRestriction
;
69 using SimpleTypeRest
= System
.Xml
.Schema
.XmlSchemaSimpleTypeRestriction
;
70 using SimpleTypeList
= System
.Xml
.Schema
.XmlSchemaSimpleTypeList
;
71 using SimpleTypeUnion
= System
.Xml
.Schema
.XmlSchemaSimpleTypeUnion
;
72 using SchemaFacet
= System
.Xml
.Schema
.XmlSchemaFacet
;
73 using LengthFacet
= System
.Xml
.Schema
.XmlSchemaLengthFacet
;
74 using MinLengthFacet
= System
.Xml
.Schema
.XmlSchemaMinLengthFacet
;
75 using Particle
= System
.Xml
.Schema
.XmlSchemaParticle
;
76 using Sequence
= System
.Xml
.Schema
.XmlSchemaSequence
;
77 using Choice
= System
.Xml
.Schema
.XmlSchemaChoice
;
78 using ValException
= System
.Xml
.Schema
.XmlSchemaValidationException
;
81 namespace System
.Xml
.Schema
83 public sealed class XmlSchemaValidator
92 static readonly XsAttribute
[] emptyAttributeArray
=
95 public XmlSchemaValidator (
96 XmlNameTable nameTable
,
98 IXmlNamespaceResolver nsResolver
,
99 ValidationFlags options
)
101 this.nameTable
= nameTable
;
102 this.schemas
= schemas
;
103 this.nsResolver
= nsResolver
;
104 this.options
= options
;
109 // XmlReader/XPathNavigator themselves
110 object nominalEventSender
;
111 IXmlLineInfo lineInfo
;
112 IXmlNamespaceResolver nsResolver
;
115 // These fields will be from XmlReaderSettings or
116 // XPathNavigator.CheckValidity(). BTW, I think we could
117 // implement XPathNavigator.CheckValidity() with
118 // XsdValidatingReader.
119 XmlNameTable nameTable
;
120 XmlSchemaSet schemas
;
121 XmlResolver xmlResolver
= new XmlUrlResolver ();
123 // "partialValidationType". but not sure how it will be used.
126 // It is perhaps from XmlReaderSettings, but XPathNavigator
128 ValidationFlags options
;
131 Transition transition
;
132 XsdParticleStateManager state
;
134 ArrayList occuredAtts
= new ArrayList ();
135 XsAttribute
[] defaultAttributes
= emptyAttributeArray
;
136 ArrayList defaultAttributesCache
= new ArrayList ();
138 #region ID Constraints
139 XsdIDManager idManager
= new XsdIDManager ();
142 #region Key Constraints
143 ArrayList keyTables
= new ArrayList ();
144 ArrayList currentKeyFieldConsumers
= new ArrayList ();
145 ArrayList tmpKeyrefPool
;
147 ArrayList elementQNameStack
= new ArrayList ();
149 StringBuilder storedCharacters
= new StringBuilder ();
150 bool shouldValidateCharacters
;
153 int xsiNilDepth
= -1;
154 int skipValidationDepth
= -1;
156 // LAMESPEC: XmlValueGetter is bogus by design because there
157 // is no way to get associated schema type for current value.
158 // Here XmlSchemaValidatingReader needs "current type"
159 // information to validate attribute values.
160 internal XmlSchemaDatatype CurrentAttributeType
;
164 #region Public properties
166 // Settable Properties
168 // IMHO It should just be an event that fires another event.
169 public event ValidationEventHandler ValidationEventHandler
;
171 public object ValidationEventSender
{
172 get { return nominalEventSender; }
173 set { nominalEventSender = value; }
176 // (kinda) Construction Properties
178 public IXmlLineInfo LineInfoProvider
{
179 get { return lineInfo; }
180 set { lineInfo = value; }
183 public XmlResolver XmlResolver
{
184 set { xmlResolver = value; }
187 public Uri SourceUri
{
188 get { return sourceUri; }
189 set { sourceUri = value; }
193 #region Private properties
195 private string BaseUri
{
196 get { return sourceUri != null ? sourceUri.AbsoluteUri : String.Empty; }
199 private XsdValidationContext Context
{
200 get { return state.Context; }
203 private bool IgnoreWarnings
{
204 get { return (options
& ValidationFlags
205 .ReportValidationWarnings
) == 0; }
208 private bool IgnoreIdentity
{
209 get { return (options
& ValidationFlags
210 .ProcessIdentityConstraints
) == 0; }
215 #region Public methods
219 public XmlSchemaAttribute
[] GetExpectedAttributes ()
221 ComplexType cType
= Context
.ActualType
as ComplexType
;
223 return emptyAttributeArray
;
224 ArrayList al
= new ArrayList ();
225 foreach (DictionaryEntry entry
in cType
.AttributeUses
)
226 if (!occuredAtts
.Contains ((QName
) entry
.Key
))
227 al
.Add (entry
.Value
);
228 return (XsAttribute
[])
229 al
.ToArray (typeof (XsAttribute
));
232 private void CollectAtomicParticles (XmlSchemaParticle p
,
235 if (p
is XmlSchemaGroupBase
) {
236 foreach (XmlSchemaParticle c
in
237 ((XmlSchemaGroupBase
) p
).Items
)
238 CollectAtomicParticles (c
, al
);
244 [MonoTODO
] // Need some tests.
245 // Its behavior is not obvious. For example, it does not
246 // contain groups (xs:sequence/xs:choice/xs:all). Since it
247 // might contain xs:any, it could not be of type element[].
248 public XmlSchemaParticle
[] GetExpectedParticles ()
250 ArrayList al
= new ArrayList ();
251 Context
.State
.GetExpectedParticles (al
);
252 ArrayList ret
= new ArrayList ();
254 foreach (XmlSchemaParticle p
in al
)
255 CollectAtomicParticles (p
, ret
);
257 return (XmlSchemaParticle
[]) ret
.ToArray (
258 typeof (XmlSchemaParticle
));
261 public void GetUnspecifiedDefaultAttributes (ArrayList defaultAttributeList
)
263 if (defaultAttributeList
== null)
264 throw new ArgumentNullException ("defaultAttributeList");
266 if (transition
!= Transition
.StartTag
)
267 throw new InvalidOperationException ("Method 'GetUnsoecifiedDefaultAttributes' works only when the validator state is inside a start tag.");
268 foreach (XmlSchemaAttribute attr
269 in GetExpectedAttributes ())
270 if (attr
.ValidatedDefaultValue
!= null || attr
.ValidatedFixedValue
!= null)
271 defaultAttributeList
.Add (attr
);
273 defaultAttributeList
.AddRange (defaultAttributes
);
278 public void AddSchema (XmlSchema schema
)
281 throw new ArgumentNullException ("schema");
282 schemas
.Add (schema
);
286 public void Initialize ()
288 transition
= Transition
.Content
;
289 state
= new XsdParticleStateManager ();
290 if (!schemas
.IsCompiled
)
294 public void Initialize (SOMObject partialValidationType
)
296 if (partialValidationType
== null)
297 throw new ArgumentNullException ("partialValidationType");
298 this.startType
= partialValidationType
;
302 // It must be called at the end of the validation (to check
303 // identity constraints etc.).
304 public void EndValidation ()
306 CheckState (Transition
.Content
);
307 transition
= Transition
.Finished
;
309 if (schemas
.Count
== 0)
313 throw new InvalidOperationException (String
.Format ("There are {0} open element(s). ValidateEndElement() must be called for each open element.", depth
));
315 // 3.3.4 ElementLocallyValidElement 7 = Root Valid.
316 if (!IgnoreIdentity
&&
317 idManager
.HasMissingIDReferences ())
318 HandleError ("There are missing ID references: " + idManager
.GetMissingIDString ());
321 // I guess it is for validation error recovery
322 [MonoTODO
] // FIXME: Find out how XmlSchemaInfo is used.
323 public void SkipToEndElement (XmlSchemaInfo info
)
325 CheckState (Transition
.Content
);
326 if (schemas
.Count
== 0)
331 public object ValidateAttribute (
334 string attributeValue
,
337 if (attributeValue
== null)
338 throw new ArgumentNullException ("attributeValue");
339 return ValidateAttribute (localName
, ns
, delegate () { return attributeValue; }
, info
);
342 // I guess this weird XmlValueGetter is for such case that
343 // value might not be required (and thus it improves
344 // performance in some cases. Doh).
346 // The return value is typed primitive, if possible.
348 public object ValidateAttribute (
351 XmlValueGetter attributeValue
,
354 if (localName
== null)
355 throw new ArgumentNullException ("localName");
357 throw new ArgumentNullException ("ns");
358 if (attributeValue
== null)
359 throw new ArgumentNullException ("attributeValue");
361 CheckState (Transition
.StartTag
);
363 QName qname
= new QName (localName
, ns
);
364 if (occuredAtts
.Contains (qname
))
365 throw new InvalidOperationException (String
.Format ("Attribute '{0}' has already been validated in the same element.", qname
));
366 occuredAtts
.Add (qname
);
368 if (ns
== XmlNamespaceManager
.XmlnsXmlns
)
371 if (schemas
.Count
== 0)
374 if (Context
.Element
!= null && Context
.XsiType
== null) {
376 // 3.3.4 Element Locally Valid (Type) - attribute
377 if (Context
.ActualType
is ComplexType
)
378 return AssessAttributeElementLocallyValidType (localName
, ns
, attributeValue
, info
);
380 HandleError ("Current simple type cannot accept attributes other than schema instance namespace.");
386 public void ValidateElement (
391 ValidateElement (localName
, ns
, info
, null, null, null, null);
394 public void ValidateElement (
400 string schemaLocation
,
401 string noNsSchemaLocation
)
403 if (localName
== null)
404 throw new ArgumentNullException ("localName");
406 throw new ArgumentNullException ("ns");
408 CheckState (Transition
.Content
);
409 transition
= Transition
.StartTag
;
411 if (schemaLocation
!= null)
412 HandleSchemaLocation (schemaLocation
);
413 if (noNsSchemaLocation
!= null)
414 HandleNoNSSchemaLocation (noNsSchemaLocation
);
416 elementQNameStack
.Add (new XmlQualifiedName (localName
, ns
));
418 if (schemas
.Count
== 0)
421 #region ID Constraints
423 idManager
.OnStartElement ();
425 defaultAttributes
= emptyAttributeArray
;
427 // If there is no schema information, then no validation is performed.
428 if (skipValidationDepth
< 0 || depth
<= skipValidationDepth
) {
429 if (shouldValidateCharacters
)
430 ValidateEndSimpleContent (null);
432 AssessOpenStartElementSchemaValidity (localName
, ns
);
436 HandleXsiNil (xsiNil
, info
);
438 HandleXsiType (xsiType
);
440 if (xsiNilDepth
< depth
)
441 shouldValidateCharacters
= true;
444 info
.IsNil
= xsiNilDepth
>= 0;
445 info
.SchemaElement
= Context
.Element
;
446 info
.SchemaType
= Context
.ActualSchemaType
;
447 info
.SchemaAttribute
= null;
448 info
.IsDefault
= false;
449 info
.MemberType
= null;
450 // FIXME: supply Validity (really useful?)
454 public object ValidateEndElement (XmlSchemaInfo info
)
456 return ValidateEndElement (info
, null);
459 // The return value is typed primitive, if supplied.
460 // Parameter 'var' seems to be converted into the type
461 // represented by current simple content type. (try passing
462 // some kind of object to this method to check the behavior.)
464 [MonoTODO
] // FIXME: Handle 'var' parameter.
465 public object ValidateEndElement (XmlSchemaInfo info
,
468 // If it is going to validate an empty element, then
469 // first validate end of attributes.
470 if (transition
== Transition
.StartTag
)
471 ValidateEndOfAttributes (info
);
473 CheckState (Transition
.Content
);
475 elementQNameStack
.RemoveAt (elementQNameStack
.Count
- 1);
477 if (schemas
.Count
== 0)
480 throw new InvalidOperationException ("There was no corresponding call to 'ValidateElement' method.");
485 if (depth
== skipValidationDepth
)
486 skipValidationDepth
= -1;
487 else if (skipValidationDepth
< 0 || depth
<= skipValidationDepth
)
488 ret
= AssessEndElementSchemaValidity (info
);
492 // StartTagCloseDeriv
493 // FIXME: fill validity inside this invocation.
494 public void ValidateEndOfAttributes (XmlSchemaInfo info
)
497 CheckState (Transition
.StartTag
);
498 transition
= Transition
.Content
;
499 if (schemas
.Count
== 0)
502 if (skipValidationDepth
< 0 || depth
<= skipValidationDepth
)
503 AssessCloseStartElementSchemaValidity (info
);
506 occuredAtts
.Clear ();
510 // LAMESPEC: It should also receive XmlSchemaInfo so that
511 // a validator application can receive simple type or
512 // or content type validation errors.
513 public void ValidateText (string value)
516 throw new ArgumentNullException ("value");
517 ValidateText (delegate () { return value; }
);
520 // TextDeriv ... without text. Maybe typed check is done by
521 // ValidateAtomicValue().
522 public void ValidateText (XmlValueGetter getter
)
525 throw new ArgumentNullException ("getter");
527 CheckState (Transition
.Content
);
528 if (schemas
.Count
== 0)
531 if (skipValidationDepth
>= 0 && depth
> skipValidationDepth
)
534 ComplexType ct
= Context
.ActualType
as ComplexType
;
536 switch (ct
.ContentType
) {
537 case XmlSchemaContentType
.Empty
:
538 HandleError ("Not allowed character content was found.");
540 case XmlSchemaContentType
.ElementOnly
:
541 string s
= storedCharacters
.ToString ();
542 if (s
.Length
> 0 && !XmlChar
.IsWhitespace (s
))
543 HandleError ("Not allowed character content was found.");
548 ValidateCharacters (getter
);
551 public void ValidateWhitespace (string value)
554 throw new ArgumentNullException ("value");
555 ValidateWhitespace (delegate () { return value; }
);
558 // TextDeriv. It should do the same as ValidateText() in our actual implementation (whitespaces are conditioned).
559 public void ValidateWhitespace (XmlValueGetter getter
)
561 ValidateText (getter
);
566 #region Error handling
568 private void HandleError (string message
)
570 HandleError (message
, null, false);
573 private void HandleError (
574 string message
, Exception innerException
)
576 HandleError (message
, innerException
, false);
579 private void HandleError (string message
,
580 Exception innerException
, bool isWarning
)
582 if (isWarning
&& IgnoreWarnings
)
585 ValException vex
= new ValException (
586 message
, nominalEventSender
, BaseUri
,
587 null, innerException
);
588 HandleError (vex
, isWarning
);
591 private void HandleError (ValException exception
)
593 HandleError (exception
, false);
596 private void HandleError (ValException exception
, bool isWarning
)
598 if (isWarning
&& IgnoreWarnings
)
601 if (ValidationEventHandler
== null)
604 ValidationEventArgs e
= new ValidationEventArgs (
607 isWarning
? XmlSeverityType
.Warning
:
608 XmlSeverityType
.Error
);
609 ValidationEventHandler (nominalEventSender
, e
);
614 private void CheckState (Transition expected
)
616 if (transition
!= expected
) {
617 if (transition
== Transition
.None
)
618 throw new InvalidOperationException ("Initialize() must be called before processing validation.");
620 throw new InvalidOperationException (
621 String
.Format ("Unexpected attempt to validate state transition from {0} to {1}.",
627 private XsElement
FindElement (string name
, string ns
)
629 return (XsElement
) schemas
.GlobalElements
[new XmlQualifiedName (name
, ns
)];
632 private XmlSchemaType
FindType (XmlQualifiedName qname
)
634 return (XmlSchemaType
) schemas
.GlobalTypes
[qname
];
637 #region Type Validation
639 private void ValidateStartElementParticle (
640 string localName
, string ns
)
642 if (Context
.State
== null)
644 Context
.XsiType
= null;
645 state
.CurrentElement
= null;
646 Context
.EvaluateStartElement (localName
,
648 if (Context
.IsInvalid
)
649 HandleError ("Invalid start element: " + ns
+ ":" + localName
);
651 Context
.PushCurrentElement (state
.CurrentElement
);
654 private void AssessOpenStartElementSchemaValidity (
655 string localName
, string ns
)
657 // If the reader is inside xsi:nil (and failed
658 // on validation), then simply skip its content.
659 if (xsiNilDepth
>= 0 && xsiNilDepth
< depth
)
660 HandleError ("Element item appeared, while current element context is nil.");
662 ValidateStartElementParticle (localName
, ns
);
664 // Create Validation Root, if not exist.
665 // [Schema Validity Assessment (Element) 1.1]
666 if (Context
.Element
== null) {
667 state
.CurrentElement
= FindElement (localName
, ns
);
668 Context
.PushCurrentElement (state
.CurrentElement
);
671 #region Key Constraints
672 if (!IgnoreIdentity
) {
673 ValidateKeySelectors ();
674 ValidateKeyFields (false, xsiNilDepth
== depth
,
675 Context
.ActualType
, null, null, null);
680 private void AssessCloseStartElementSchemaValidity (XmlSchemaInfo info
)
682 if (Context
.XsiType
!= null)
683 AssessCloseStartElementLocallyValidType (info
);
684 else if (Context
.Element
!= null) {
685 // element locally valid is checked only when
686 // xsi:type does not exist.
687 AssessElementLocallyValidElement ();
688 if (Context
.Element
.ElementType
!= null)
689 AssessCloseStartElementLocallyValidType (info
);
692 if (Context
.Element
== null) {
693 switch (state
.ProcessContents
) {
694 case ContentProc
.Skip
:
696 case ContentProc
.Lax
:
699 QName current
= (QName
) elementQNameStack
[elementQNameStack
.Count
- 1];
700 if (Context
.XsiType
== null &&
701 (schemas
.Contains (current
.Namespace
) ||
702 !schemas
.MissedSubComponents (current
.Namespace
)))
703 HandleError ("Element declaration for " + current
+ " is missing.");
708 // Proceed to the next depth.
710 state
.PushContext ();
712 XsdValidationState next
= null;
713 if (state
.ProcessContents
== ContentProc
.Skip
)
714 skipValidationDepth
= depth
;
716 // create child particle state.
717 ComplexType xsComplexType
= Context
.ActualType
as ComplexType
;
718 if (xsComplexType
!= null)
719 next
= state
.Create (xsComplexType
.ValidatableParticle
);
720 else if (state
.ProcessContents
== ContentProc
.Lax
)
721 next
= state
.Create (XmlSchemaAny
.AnyTypeContent
);
723 next
= state
.Create (XmlSchemaParticle
.Empty
);
725 Context
.State
= next
;
728 // It must be invoked after xsi:nil turned out not to be in
730 private void AssessElementLocallyValidElement ()
732 XsElement element
= Context
.Element
;
733 XmlQualifiedName qname
= (XmlQualifiedName
) elementQNameStack
[elementQNameStack
.Count
- 1];
736 HandleError ("Element declaration is required for " + qname
);
738 if (element
.ActualIsAbstract
)
739 HandleError ("Abstract element declaration was specified for " + qname
);
740 // 3. is checked inside ValidateAttribute().
743 // 3.3.4 Element Locally Valid (Type)
744 private void AssessCloseStartElementLocallyValidType (XmlSchemaInfo info
)
746 object schemaType
= Context
.ActualType
;
747 if (schemaType
== null) { // 1.
748 HandleError ("Schema type does not exist.");
751 ComplexType cType
= schemaType
as ComplexType
;
752 SimpleType sType
= schemaType
as SimpleType
;
755 // Attributes are checked in ValidateAttribute().
756 } else if (cType
!= null) {
757 // 3.2. Also, 2. is checked there.
758 AssessCloseStartElementLocallyValidComplexType (cType
, info
);
762 // 3.4.4 Element Locally Valid (Complex Type)
763 // FIXME: use SchemaInfo for somewhere (? it is passed to ValidateEndOfAttributes() for some reason)
764 private void AssessCloseStartElementLocallyValidComplexType (ComplexType cType
, XmlSchemaInfo info
)
767 if (cType
.IsAbstract
) {
768 HandleError ("Target complex type is abstract.");
772 // 2 (xsi:nil and content prohibition)
773 // See AssessStartElementSchemaValidity() and ValidateCharacters()
774 // 3. attribute uses and 5. wild IDs are handled at
775 // ValidateAttribute(), except for default/fixed values.
777 // Collect default attributes.
779 foreach (XsAttribute attr
in GetExpectedAttributes ()) {
780 if (attr
.ValidatedUse
== XmlSchemaUse
.Required
&&
781 attr
.ValidatedFixedValue
== null)
782 HandleError ("Required attribute " + attr
.QualifiedName
+ " was not found.");
783 else if (attr
.ValidatedDefaultValue
!= null || attr
.ValidatedFixedValue
!= null)
784 defaultAttributesCache
.Add (attr
);
786 if (defaultAttributesCache
.Count
== 0)
787 defaultAttributes
= emptyAttributeArray
;
789 defaultAttributes
= (XsAttribute
[])
790 defaultAttributesCache
.ToArray (
791 typeof (XsAttribute
));
792 defaultAttributesCache
.Clear ();
793 // 5. wild IDs was already checked at ValidateAttribute().
795 // 3. - handle default attributes
796 #region ID Constraints
797 if (!IgnoreIdentity
) {
798 foreach (XsAttribute a
in defaultAttributes
) {
799 var atype
= a
.AttributeType
as XmlSchemaDatatype
?? a
.AttributeSchemaType
.Datatype
;
800 object avalue
= a
.ValidatedFixedValue
?? a
.ValidatedDefaultValue
;
801 string error
= idManager
.AssessEachAttributeIdentityConstraint (atype
, avalue
, ((QName
) elementQNameStack
[elementQNameStack
.Count
- 1]).Name
);
808 #region Key Constraints
810 foreach (XsAttribute a
in defaultAttributes
)
811 ValidateKeyFieldsAttribute (a
, a
.ValidatedFixedValue
?? a
.ValidatedDefaultValue
);
815 private object AssessAttributeElementLocallyValidType (string localName
, string ns
, XmlValueGetter getter
, XmlSchemaInfo info
)
817 ComplexType cType
= Context
.ActualType
as ComplexType
;
818 XmlQualifiedName qname
= new XmlQualifiedName (localName
, ns
);
819 // including 3.10.4 Item Valid (Wildcard)
820 XmlSchemaObject attMatch
= XmlSchemaUtil
.FindAttributeDeclaration (ns
, schemas
, cType
, qname
);
821 if (attMatch
== null)
822 HandleError ("Attribute declaration was not found for " + qname
);
823 XsAttribute attdecl
= attMatch
as XsAttribute
;
824 if (attdecl
!= null) {
825 AssessAttributeLocallyValidUse (attdecl
);
826 return AssessAttributeLocallyValid (attdecl
, info
, getter
);
827 } // otherwise anyAttribute or null.
831 // 3.2.4 Attribute Locally Valid and 3.4.4
832 private object AssessAttributeLocallyValid (XsAttribute attr
, XmlSchemaInfo info
, XmlValueGetter getter
)
835 if (attr
.AttributeType
== null)
836 HandleError ("Attribute type is missing for " + attr
.QualifiedName
);
837 XsDatatype dt
= attr
.AttributeType
as XsDatatype
;
839 dt
= ((SimpleType
) attr
.AttributeType
).Datatype
;
841 object parsedValue
= null;
843 // It is a bit heavy process, so let's omit as long as possible ;-)
844 if (dt
!= SimpleType
.AnySimpleType
|| attr
.ValidatedFixedValue
!= null) {
846 CurrentAttributeType
= dt
;
847 parsedValue
= getter ();
848 } catch (Exception ex
) { // It is inevitable and bad manner.
849 HandleError (String
.Format ("Attribute value is invalid against its data type {0}", dt
!= null ? dt
.TokenizedType
: default (XmlTokenizedType
)), ex
);
852 // check part of 3.14.4 StringValid
853 SimpleType st
= attr
.AttributeType
as SimpleType
;
855 ValidateRestrictedSimpleTypeValue (st
, ref dt
, new XmlAtomicValue (parsedValue
, attr
.AttributeSchemaType
).Value
);
857 if (attr
.ValidatedFixedValue
!= null) {
858 if (!XmlSchemaUtil
.AreSchemaDatatypeEqual (attr
.AttributeSchemaType
, attr
.ValidatedFixedTypedValue
, attr
.AttributeSchemaType
, parsedValue
))
859 HandleError (String
.Format ("The value of the attribute {0} does not match with its fixed value '{1}' in the space of type {2}", attr
.QualifiedName
, attr
.ValidatedFixedValue
, dt
));
860 parsedValue
= attr
.ValidatedFixedTypedValue
;
864 #region ID Constraints
865 if (!IgnoreIdentity
) {
866 string error
= idManager
.AssessEachAttributeIdentityConstraint (dt
, parsedValue
, ((QName
) elementQNameStack
[elementQNameStack
.Count
- 1]).Name
);
872 #region Key Constraints
874 ValidateKeyFieldsAttribute (attr
, parsedValue
);
880 private void AssessAttributeLocallyValidUse (XsAttribute attr
)
882 // This is extra check than spec 3.5.4
883 if (attr
.ValidatedUse
== XmlSchemaUse
.Prohibited
)
884 HandleError ("Attribute " + attr
.QualifiedName
+ " is prohibited in this context.");
887 private object AssessEndElementSchemaValidity (
890 object ret
= ValidateEndSimpleContent (info
);
892 ValidateEndElementParticle (); // validate against childrens' state.
894 // 3.3.4 Assess ElementLocallyValidElement 5: value constraints.
895 // 3.3.4 Assess ElementLocallyValidType 3.1.3. = StringValid(3.14.4)
896 // => ValidateEndSimpleContent ().
898 #region Key Constraints
900 ValidateEndElementKeyConstraints ();
903 // Reset xsi:nil, if required.
904 if (xsiNilDepth
== depth
)
909 private void ValidateEndElementParticle ()
911 if (Context
.State
!= null) {
912 if (!Context
.EvaluateEndElement ()) {
913 HandleError ("Invalid end element. There are still required content items.");
916 Context
.PopCurrentElement ();
918 Context
.XsiType
= null; // FIXME: this is hack. should be stacked as well as element.
921 // Utility for missing validation completion related to child items.
922 private void ValidateCharacters (XmlValueGetter getter
)
924 if (xsiNilDepth
>= 0 && xsiNilDepth
< depth
)
925 HandleError ("Element item appeared, while current element context is nil.");
927 if (shouldValidateCharacters
) {
928 CurrentAttributeType
= null;
929 storedCharacters
.Append (getter ());
934 // Utility for missing validation completion related to child items.
935 private object ValidateEndSimpleContent (XmlSchemaInfo info
)
938 if (shouldValidateCharacters
)
939 ret
= ValidateEndSimpleContentCore (info
);
940 shouldValidateCharacters
= false;
941 storedCharacters
.Length
= 0;
945 private object ValidateEndSimpleContentCore (XmlSchemaInfo info
)
947 if (Context
.ActualType
== null)
950 string value = storedCharacters
.ToString ();
953 if (value.Length
== 0) {
954 // 3.3.4 Element Locally Valid (Element) 5.1.2
955 if (Context
.Element
!= null) {
956 if (Context
.Element
.ValidatedDefaultValue
!= null)
957 value = Context
.Element
.ValidatedDefaultValue
;
961 XsDatatype dt
= Context
.ActualType
as XsDatatype
;
962 SimpleType st
= Context
.ActualType
as SimpleType
;
967 ComplexType ct
= Context
.ActualType
as ComplexType
;
969 switch (ct
.ContentType
) {
970 case XmlSchemaContentType
.ElementOnly
:
971 if (value.Length
> 0 && !XmlChar
.IsWhitespace (value))
972 HandleError ("Character content not allowed in an elementOnly model.");
974 case XmlSchemaContentType
.Empty
:
975 if (value.Length
> 0)
976 HandleError ("Character content not allowed in an empty model.");
982 // 3.3.4 Element Locally Valid (Element) :: 5.2.2.2. Fixed value constraints
983 if (Context
.Element
!= null && Context
.Element
.ValidatedFixedValue
!= null)
984 if (value != Context
.Element
.ValidatedFixedValue
)
985 HandleError ("Fixed value constraint was not satisfied.");
986 ret
= AssessStringValid (st
, dt
, value);
989 #region Key Constraints
991 ValidateSimpleContentIdentity (dt
, value);
994 shouldValidateCharacters
= false;
997 info
.IsNil
= xsiNilDepth
>= 0;
998 info
.SchemaElement
= null;
999 info
.SchemaType
= Context
.ActualType
as XmlSchemaType
;
1000 if (info
.SchemaType
== null)
1001 info
.SchemaType
= XmlSchemaType
.GetBuiltInSimpleType (dt
.TypeCode
);
1002 info
.SchemaAttribute
= null;
1003 info
.IsDefault
= false; // FIXME: might be true
1004 info
.MemberType
= null; // FIXME: check
1005 // FIXME: supply Validity (really useful?)
1011 // 3.14.4 String Valid
1012 private object AssessStringValid (SimpleType st
,
1013 XsDatatype dt
, string value)
1015 XsDatatype validatedDatatype
= dt
;
1018 string normalized
= validatedDatatype
.Normalize (value);
1020 XsDatatype itemDatatype
;
1021 SimpleType itemSimpleType
;
1022 switch (st
.DerivedBy
) {
1023 case XmlSchemaDerivationMethod
.List
:
1024 SimpleTypeList listContent
= st
.Content
as SimpleTypeList
;
1025 values
= normalized
.Split (XmlChar
.WhitespaceChars
);
1026 // LAMESPEC: Types of each element in
1027 // the returned list might be
1028 // inconsistent, so basically returning
1029 // value does not make sense without
1030 // explicit runtime type information
1031 // for base primitive type.
1032 object [] retValues
= new object [values
.Length
];
1033 itemDatatype
= listContent
.ValidatedListItemType
as XsDatatype
;
1034 itemSimpleType
= listContent
.ValidatedListItemType
as SimpleType
;
1035 for (int vi
= 0; vi
< values
.Length
; vi
++) {
1036 string each
= values
[vi
];
1037 if (each
== String
.Empty
)
1039 // validate against ValidatedItemType
1040 if (itemDatatype
!= null) {
1042 retValues
[vi
] = itemDatatype
.ParseValue (each
, nameTable
, nsResolver
);
1043 } catch (Exception ex
) { // It is inevitable and bad manner.
1044 HandleError ("List type value contains one or more invalid values.", ex
);
1049 AssessStringValid (itemSimpleType
, itemSimpleType
.Datatype
, each
);
1053 case XmlSchemaDerivationMethod
.Union
:
1054 SimpleTypeUnion union
= st
.Content
as SimpleTypeUnion
;
1056 string each
= normalized
;
1057 // validate against ValidatedItemType
1058 bool passed
= false;
1059 foreach (object eachType
in union
.ValidatedTypes
) {
1060 itemDatatype
= eachType
as XsDatatype
;
1061 itemSimpleType
= eachType
as SimpleType
;
1062 if (itemDatatype
!= null) {
1064 ret
= itemDatatype
.ParseValue (each
, nameTable
, nsResolver
);
1065 } catch (Exception
) { // It is inevitable and bad manner.
1071 ret
= AssessStringValid (itemSimpleType
, itemSimpleType
.Datatype
, each
);
1072 } catch (ValException
) {
1080 HandleError ("Union type value contains one or more invalid values.");
1085 case XmlSchemaDerivationMethod
.Restriction
:
1086 SimpleTypeRest str
= st
.Content
as SimpleTypeRest
;
1089 /* Don't forget to validate against inherited type's facets
1090 * Could we simplify this by assuming that the basetype will also
1093 // mmm, will check later.
1094 SimpleType baseType
= st
.BaseXmlSchemaType
as SimpleType
;
1095 if (baseType
!= null) {
1096 ret
= AssessStringValid (baseType
, dt
, value);
1098 if (!str
.ValidateValueWithFacets (value, nameTable
, nsResolver
)) {
1099 HandleError ("Specified value was invalid against the facets.");
1103 validatedDatatype
= st
.Datatype
;
1107 if (validatedDatatype
!= null) {
1109 ret
= validatedDatatype
.ParseValue (value, nameTable
, nsResolver
);
1110 } catch (Exception ex
) { // It is inevitable and bad manner.
1111 HandleError (String
.Format ("Invalidly typed data was specified."), ex
);
1117 private void ValidateRestrictedSimpleTypeValue (SimpleType st
, ref XsDatatype dt
, string normalized
)
1121 XsDatatype itemDatatype
;
1122 SimpleType itemSimpleType
;
1123 switch (st
.DerivedBy
) {
1124 case XmlSchemaDerivationMethod
.List
:
1125 SimpleTypeList listContent
= st
.Content
as SimpleTypeList
;
1126 values
= normalized
.Split (XmlChar
.WhitespaceChars
);
1127 itemDatatype
= listContent
.ValidatedListItemType
as XsDatatype
;
1128 itemSimpleType
= listContent
.ValidatedListItemType
as SimpleType
;
1129 for (int vi
= 0; vi
< values
.Length
; vi
++) {
1130 string each
= values
[vi
];
1131 if (each
== String
.Empty
)
1133 // validate against ValidatedItemType
1134 if (itemDatatype
!= null) {
1136 itemDatatype
.ParseValue (each
, nameTable
, nsResolver
);
1137 } catch (Exception ex
) { // FIXME: (wishlist) better exception handling ;-(
1138 HandleError ("List type value contains one or more invalid values.", ex
);
1143 AssessStringValid (itemSimpleType
, itemSimpleType
.Datatype
, each
);
1146 case XmlSchemaDerivationMethod
.Union
:
1147 SimpleTypeUnion union
= st
.Content
as SimpleTypeUnion
;
1149 string each
= normalized
;
1150 // validate against ValidatedItemType
1151 bool passed
= false;
1152 foreach (object eachType
in union
.ValidatedTypes
) {
1153 itemDatatype
= eachType
as XsDatatype
;
1154 itemSimpleType
= eachType
as SimpleType
;
1155 if (itemDatatype
!= null) {
1157 itemDatatype
.ParseValue (each
, nameTable
, nsResolver
);
1158 } catch (Exception
) { // FIXME: (wishlist) better exception handling ;-(
1164 AssessStringValid (itemSimpleType
, itemSimpleType
.Datatype
, each
);
1165 } catch (ValException
) {
1173 HandleError ("Union type value contains one or more invalid values.");
1178 case XmlSchemaDerivationMethod
.Restriction
:
1179 SimpleTypeRest str
= st
.Content
as SimpleTypeRest
;
1182 /* Don't forget to validate against inherited type's facets
1183 * Could we simplify this by assuming that the basetype will also
1186 // mmm, will check later.
1187 SimpleType baseType
= st
.BaseXmlSchemaType
as SimpleType
;
1188 if (baseType
!= null) {
1189 AssessStringValid(baseType
, dt
, normalized
);
1191 if (!str
.ValidateValueWithFacets (normalized
, nameTable
, nsResolver
)) {
1192 HandleError ("Specified value was invalid against the facets.");
1204 #region Key Constraints Validation
1205 private XsdKeyTable
CreateNewKeyTable (XmlSchemaIdentityConstraint ident
)
1207 XsdKeyTable seq
= new XsdKeyTable (ident
);
1208 seq
.StartDepth
= depth
;
1209 this.keyTables
.Add (seq
);
1213 // 3.11.4 Identity Constraint Satisfied
1214 private void ValidateKeySelectors ()
1216 if (tmpKeyrefPool
!= null)
1217 tmpKeyrefPool
.Clear ();
1218 if (Context
.Element
!= null && Context
.Element
.Constraints
.Count
> 0) {
1219 // (a) Create new key sequences, if required.
1220 for (int i
= 0; i
< Context
.Element
.Constraints
.Count
; i
++) {
1221 XmlSchemaIdentityConstraint ident
= (XmlSchemaIdentityConstraint
) Context
.Element
.Constraints
[i
];
1222 XsdKeyTable seq
= CreateNewKeyTable (ident
);
1223 if (ident
is XmlSchemaKeyref
) {
1224 if (tmpKeyrefPool
== null)
1225 tmpKeyrefPool
= new ArrayList ();
1226 tmpKeyrefPool
.Add (seq
);
1231 // (b) Evaluate current key sequences.
1232 for (int i
= 0; i
< keyTables
.Count
; i
++) {
1233 XsdKeyTable seq
= (XsdKeyTable
) keyTables
[i
];
1234 if (seq
.SelectorMatches (this.elementQNameStack
, depth
) != null) {
1235 // creates and registers new entry.
1236 XsdKeyEntry entry
= new XsdKeyEntry (seq
, depth
, lineInfo
);
1237 seq
.Entries
.Add (entry
);
1242 private void ValidateKeyFieldsAttribute (XsAttribute attr
, object value)
1244 ValidateKeyFields (true, false, attr
.AttributeType
, attr
.QualifiedName
.Name
, attr
.QualifiedName
.Namespace
, value);
1247 private void ValidateKeyFields (bool isAttr
, bool isNil
, object schemaType
, string attrName
, string attrNs
, object value)
1249 // (c) Evaluate field paths.
1250 for (int i
= 0; i
< keyTables
.Count
; i
++) {
1251 XsdKeyTable seq
= (XsdKeyTable
) keyTables
[i
];
1252 // If possible, create new field entry candidates.
1253 for (int j
= 0; j
< seq
.Entries
.Count
; j
++) {
1254 CurrentAttributeType
= null;
1256 seq
.Entries
[j
].ProcessMatch (
1265 isAttr
? depth
+ 1 : depth
,
1270 currentKeyFieldConsumers
);
1271 } catch (ValException ex
) {
1278 private void ValidateEndElementKeyConstraints ()
1280 // Reset Identity constraints.
1281 for (int i
= 0; i
< keyTables
.Count
; i
++) {
1282 XsdKeyTable seq
= this.keyTables
[i
] as XsdKeyTable
;
1283 if (seq
.StartDepth
== depth
) {
1284 ValidateEndKeyConstraint (seq
);
1286 for (int k
= 0; k
< seq
.Entries
.Count
; k
++) {
1287 XsdKeyEntry entry
= seq
.Entries
[k
] as XsdKeyEntry
;
1288 // Remove finished (maybe key not found) entries.
1289 if (entry
.StartDepth
== depth
) {
1291 seq
.FinishedEntries
.Add (entry
);
1292 else if (seq
.SourceSchemaIdentity
is XmlSchemaKey
)
1293 HandleError ("Key sequence is missing.");
1294 seq
.Entries
.RemoveAt (k
);
1297 // Pop validated key depth to find two or more fields.
1299 for (int j
= 0; j
< entry
.KeyFields
.Count
; j
++) {
1300 XsdKeyEntryField kf
= entry
.KeyFields
[j
];
1301 if (!kf
.FieldFound
&& kf
.FieldFoundDepth
== depth
) {
1302 kf
.FieldFoundDepth
= 0;
1303 kf
.FieldFoundPath
= null;
1310 for (int i
= 0; i
< keyTables
.Count
; i
++) {
1311 XsdKeyTable seq
= this.keyTables
[i
] as XsdKeyTable
;
1312 if (seq
.StartDepth
== depth
) {
1313 keyTables
.RemoveAt (i
);
1319 private void ValidateEndKeyConstraint (XsdKeyTable seq
)
1321 ArrayList errors
= new ArrayList ();
1322 for (int i
= 0; i
< seq
.Entries
.Count
; i
++) {
1323 XsdKeyEntry entry
= (XsdKeyEntry
) seq
.Entries
[i
];
1326 if (seq
.SourceSchemaIdentity
is XmlSchemaKey
)
1327 errors
.Add ("line " + entry
.SelectorLineNumber
+ "position " + entry
.SelectorLinePosition
);
1329 if (errors
.Count
> 0)
1330 HandleError ("Invalid identity constraints were found. Key was not found. "
1331 + String
.Join (", ", errors
.ToArray (typeof (string)) as string []));
1334 // Find reference target
1335 XmlSchemaKeyref xsdKeyref
= seq
.SourceSchemaIdentity
as XmlSchemaKeyref
;
1336 if (xsdKeyref
!= null) {
1337 for (int i
= this.keyTables
.Count
- 1; i
>= 0; i
--) {
1338 XsdKeyTable target
= this.keyTables
[i
] as XsdKeyTable
;
1339 if (target
.SourceSchemaIdentity
== xsdKeyref
.Target
) {
1340 seq
.ReferencedKey
= target
;
1341 for (int j
= 0; j
< seq
.FinishedEntries
.Count
; j
++) {
1342 XsdKeyEntry entry
= (XsdKeyEntry
) seq
.FinishedEntries
[j
];
1343 for (int k
= 0; k
< target
.FinishedEntries
.Count
; k
++) {
1344 XsdKeyEntry targetEntry
= (XsdKeyEntry
) target
.FinishedEntries
[k
];
1345 if (entry
.CompareIdentity (targetEntry
)) {
1346 entry
.KeyRefFound
= true;
1353 if (seq
.ReferencedKey
== null)
1354 HandleError ("Target key was not found.");
1355 for (int i
= 0; i
< seq
.FinishedEntries
.Count
; i
++) {
1356 XsdKeyEntry entry
= (XsdKeyEntry
) seq
.FinishedEntries
[i
];
1357 if (!entry
.KeyRefFound
)
1358 errors
.Add (" line " + entry
.SelectorLineNumber
+ ", position " + entry
.SelectorLinePosition
);
1360 if (errors
.Count
> 0)
1361 HandleError ("Invalid identity constraints were found. Referenced key was not found: "
1362 + String
.Join (" / ", errors
.ToArray (typeof (string)) as string []));
1366 private void ValidateSimpleContentIdentity (
1367 XmlSchemaDatatype dt
, string value)
1369 // Identity field value
1370 if (currentKeyFieldConsumers
!= null) {
1371 while (this.currentKeyFieldConsumers
.Count
> 0) {
1372 XsdKeyEntryField field
= this.currentKeyFieldConsumers
[0] as XsdKeyEntryField
;
1373 if (field
.Identity
!= null)
1374 HandleError ("Two or more identical field was found. Former value is '" + field
.Identity
+ "' .");
1375 object identity
= null; // This means empty value
1378 identity
= dt
.ParseValue (value, nameTable
, nsResolver
);
1379 } catch (Exception ex
) { // It is inevitable and bad manner.
1380 HandleError ("Identity value is invalid against its data type " + dt
.TokenizedType
, ex
);
1383 if (identity
== null)
1386 if (!field
.SetIdentityField (identity
, depth
== xsiNilDepth
, dt
as XsdAnySimpleType
, depth
, lineInfo
))
1387 HandleError ("Two or more identical key value was found: '" + value + "' .");
1388 this.currentKeyFieldConsumers
.RemoveAt (0);
1395 private object GetXsiType (string name
)
1397 object xsiType
= null;
1398 XmlQualifiedName typeQName
=
1399 XmlQualifiedName
.Parse (name
, nsResolver
, true);
1400 if (typeQName
== ComplexType
.AnyTypeName
)
1401 xsiType
= ComplexType
.AnyType
;
1402 else if (XmlSchemaUtil
.IsBuiltInDatatypeName (typeQName
))
1403 xsiType
= XsDatatype
.FromName (typeQName
);
1405 xsiType
= FindType (typeQName
);
1409 private void HandleXsiType (string typename
)
1411 XsElement element
= Context
.Element
;
1412 object xsiType
= GetXsiType (typename
);
1413 if (xsiType
== null) {
1414 HandleError ("The instance type was not found: " + typename
);
1417 XmlSchemaType xsiSchemaType
= xsiType
as XmlSchemaType
;
1418 if (xsiSchemaType
!= null && Context
.Element
!= null) {
1419 XmlSchemaType elemBaseType
= element
.ElementType
as XmlSchemaType
;
1420 if (elemBaseType
!= null && (xsiSchemaType
.DerivedBy
& elemBaseType
.FinalResolved
) != 0)
1421 HandleError ("The instance type is prohibited by the type of the context element.");
1422 if (elemBaseType
!= xsiType
&& (xsiSchemaType
.DerivedBy
& element
.BlockResolved
) != 0)
1423 HandleError ("The instance type is prohibited by the context element.");
1425 ComplexType xsiComplexType
= xsiType
as ComplexType
;
1426 if (xsiComplexType
!= null && xsiComplexType
.IsAbstract
)
1427 HandleError ("The instance type is abstract: " + typename
);
1429 // If current schema type exists, then this xsi:type must be
1430 // valid extension of that type. See 1.2.1.2.4.
1431 if (element
!= null) {
1432 AssessLocalTypeDerivationOK (xsiType
, element
.ElementType
, element
.BlockResolved
);
1434 // See also ValidateEndOfAttributes().
1435 Context
.XsiType
= xsiType
;
1439 // It is common to ElementLocallyValid::4 and SchemaValidityAssessment::1.2.1.2.4
1440 private void AssessLocalTypeDerivationOK (object xsiType
, object baseType
, XmlSchemaDerivationMethod flag
)
1442 XmlSchemaType xsiSchemaType
= xsiType
as XmlSchemaType
;
1443 ComplexType baseComplexType
= baseType
as ComplexType
;
1444 ComplexType xsiComplexType
= xsiSchemaType
as ComplexType
;
1445 if (xsiType
!= baseType
) {
1446 // Extracted (not extraneous) check for 3.4.6 TypeDerivationOK.
1447 if (baseComplexType
!= null)
1448 flag
|= baseComplexType
.BlockResolved
;
1449 if (flag
== XmlSchemaDerivationMethod
.All
) {
1450 HandleError ("Prohibited element type substitution.");
1452 } else if (xsiSchemaType
!= null && (flag
& xsiSchemaType
.DerivedBy
) != 0) {
1453 HandleError ("Prohibited element type substitution.");
1458 if (xsiComplexType
!= null)
1460 xsiComplexType
.ValidateTypeDerivationOK (baseType
, null, null);
1461 } catch (ValException ex
) {
1465 SimpleType xsiSimpleType
= xsiType
as SimpleType
;
1466 if (xsiSimpleType
!= null) {
1468 xsiSimpleType
.ValidateTypeDerivationOK (baseType
, null, null, true);
1469 } catch (ValException ex
) {
1473 else if (xsiType
is XsDatatype
) {
1477 HandleError ("Primitive data type cannot be derived type using xsi:type specification.");
1482 private void HandleXsiNil (string value, XmlSchemaInfo info
)
1484 XsElement element
= Context
.Element
;
1485 if (!element
.ActualIsNillable
) {
1486 HandleError (String
.Format ("Current element '{0}' is not nillable and thus does not allow occurence of 'nil' attribute.", Context
.Element
.QualifiedName
));
1489 value = value.Trim (XmlChar
.WhitespaceChars
);
1491 // Note that 3.2.1 xsi:nil constraints are to be
1492 // validated in AssessElementSchemaValidity() and
1493 // ValidateCharacters().
1494 if (value == "true") {
1495 if (element
.ValidatedFixedValue
!= null)
1496 HandleError ("Schema instance nil was specified, where the element declaration for " + element
.QualifiedName
+ "has fixed value constraints.");
1497 xsiNilDepth
= depth
;
1503 #region External schema resolution
1505 private XmlSchema
ReadExternalSchema (string uri
)
1507 Uri absUri
= new Uri (SourceUri
, uri
.Trim (XmlChar
.WhitespaceChars
));
1508 XmlTextReader xtr
= null;
1510 xtr
= new XmlTextReader (absUri
.ToString (),
1511 (Stream
) xmlResolver
.GetEntity (
1512 absUri
, null, typeof (Stream
)),
1514 return XmlSchema
.Read (
1515 xtr
, ValidationEventHandler
);
1522 private void HandleSchemaLocation (string schemaLocation
)
1524 if (xmlResolver
== null)
1526 XmlSchema schema
= null;
1527 bool schemaAdded
= false;
1528 string [] tmp
= null;
1530 schemaLocation
= XmlSchemaType
.GetBuiltInSimpleType (XmlTypeCode
.Token
).Datatype
.ParseValue (schemaLocation
, null, null) as string;
1531 tmp
= schemaLocation
.Split (XmlChar
.WhitespaceChars
);
1532 } catch (Exception ex
) {
1533 HandleError ("Invalid schemaLocation attribute format.", ex
, true);
1534 tmp
= new string [0];
1536 if (tmp
.Length
% 2 != 0)
1537 HandleError ("Invalid schemaLocation attribute format.");
1538 for (int i
= 0; i
< tmp
.Length
; i
+= 2) {
1540 schema
= ReadExternalSchema (tmp
[i
+ 1]);
1541 } catch (Exception ex
) { // It is inevitable and bad manner.
1542 HandleError ("Could not resolve schema location URI: " + schemaLocation
, ex
, true);
1545 if (schema
.TargetNamespace
== null)
1546 schema
.TargetNamespace
= tmp
[i
];
1547 else if (schema
.TargetNamespace
!= tmp
[i
])
1548 HandleError ("Specified schema has different target namespace.");
1550 if (schema
!= null) {
1551 if (!schemas
.Contains (schema
.TargetNamespace
)) {
1553 schemas
.Add (schema
);
1561 private void HandleNoNSSchemaLocation (string noNsSchemaLocation
)
1563 if (xmlResolver
== null)
1565 XmlSchema schema
= null;
1566 bool schemaAdded
= false;
1569 schema
= ReadExternalSchema (noNsSchemaLocation
);
1570 } catch (Exception ex
) { // It is inevitable and bad manner.
1571 HandleError ("Could not resolve schema location URI: " + noNsSchemaLocation
, ex
, true);
1573 if (schema
!= null && schema
.TargetNamespace
!= null)
1574 HandleError ("Specified schema has different target namespace.");
1576 if (schema
!= null) {
1577 if (!schemas
.Contains (schema
.TargetNamespace
)) {
1579 schemas
.Add (schema
);