XmlSchemaValidator.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  1. //
  2. // XmlSchemaValidator.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // (C)2004 Novell Inc,
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. //
  30. // LAMESPEC:
  31. // - There is no assurance that xsi:type precedes to any other attributes,
  32. // or xsi:type is not handled.
  33. // - There is no SourceUri provision.
  34. //
  35. #if NET_2_0
  36. using System;
  37. using System.Collections;
  38. using System.IO;
  39. using System.Text;
  40. using System.Xml;
  41. using Mono.Xml.Schema;
  42. using QName = System.Xml.XmlQualifiedName;
  43. using Form = System.Xml.Schema.XmlSchemaForm;
  44. using Use = System.Xml.Schema.XmlSchemaUse;
  45. using ContentType = System.Xml.Schema.XmlSchemaContentType;
  46. using Validity = System.Xml.Schema.XmlSchemaValidity;
  47. using ValidationFlags = System.Xml.Schema.XmlSchemaValidationFlags;
  48. using ContentProc = System.Xml.Schema.XmlSchemaContentProcessing;
  49. using SOMList = System.Xml.Schema.XmlSchemaObjectCollection;
  50. using SOMObject = System.Xml.Schema.XmlSchemaObject;
  51. using XsElement = System.Xml.Schema.XmlSchemaElement;
  52. using XsAttribute = System.Xml.Schema.XmlSchemaAttribute;
  53. using AttrGroup = System.Xml.Schema.XmlSchemaAttributeGroup;
  54. using AttrGroupRef = System.Xml.Schema.XmlSchemaAttributeGroupRef;
  55. using XsDatatype = System.Xml.Schema.XmlSchemaDatatype;
  56. using SimpleType = System.Xml.Schema.XmlSchemaSimpleType;
  57. using ComplexType = System.Xml.Schema.XmlSchemaComplexType;
  58. using SimpleModel = System.Xml.Schema.XmlSchemaSimpleContent;
  59. using SimpleExt = System.Xml.Schema.XmlSchemaSimpleContentExtension;
  60. using SimpleRst = System.Xml.Schema.XmlSchemaSimpleContentRestriction;
  61. using ComplexModel = System.Xml.Schema.XmlSchemaComplexContent;
  62. using ComplexExt = System.Xml.Schema.XmlSchemaComplexContentExtension;
  63. using ComplexRst = System.Xml.Schema.XmlSchemaComplexContentRestriction;
  64. using SimpleTypeRest = System.Xml.Schema.XmlSchemaSimpleTypeRestriction;
  65. using SimpleTypeList = System.Xml.Schema.XmlSchemaSimpleTypeList;
  66. using SimpleTypeUnion = System.Xml.Schema.XmlSchemaSimpleTypeUnion;
  67. using SchemaFacet = System.Xml.Schema.XmlSchemaFacet;
  68. using LengthFacet = System.Xml.Schema.XmlSchemaLengthFacet;
  69. using MinLengthFacet = System.Xml.Schema.XmlSchemaMinLengthFacet;
  70. using Particle = System.Xml.Schema.XmlSchemaParticle;
  71. using Sequence = System.Xml.Schema.XmlSchemaSequence;
  72. using Choice = System.Xml.Schema.XmlSchemaChoice;
  73. using ValException = System.Xml.Schema.XmlSchemaValidationException;
  74. namespace System.Xml.Schema
  75. {
  76. public class XmlSchemaValidator
  77. {
  78. enum Transition {
  79. None,
  80. Content,
  81. StartTag,
  82. Finished
  83. }
  84. static readonly XsAttribute [] emptyAttributeArray =
  85. new XsAttribute [0];
  86. public XmlSchemaValidator (
  87. XmlNameTable nameTable,
  88. XmlSchemaSet schemas,
  89. IXmlNamespaceResolver nsResolver,
  90. ValidationFlags options)
  91. {
  92. this.nameTable = nameTable;
  93. this.schemas = schemas;
  94. this.nsResolver = nsResolver;
  95. this.options = options;
  96. }
  97. #region Fields
  98. // XmlReader/XPathNavigator themselves
  99. object nominalEventSender;
  100. IXmlLineInfo lineInfo;
  101. IXmlNamespaceResolver nsResolver;
  102. string sourceUri;
  103. // These fields will be from XmlReaderSettings or
  104. // XPathNavigator.CheckValidity(). BTW, I think we could
  105. // implement XPathNavigator.CheckValidity() with
  106. // XsdValidatingReader.
  107. XmlNameTable nameTable;
  108. XmlSchemaSet schemas;
  109. XmlResolver xmlResolver = new XmlUrlResolver ();
  110. // "partialValidationType". but not sure how it will be used.
  111. SOMObject startType;
  112. // It is perhaps from XmlReaderSettings, but XPathNavigator
  113. // does not have it.
  114. ValidationFlags options;
  115. // Validation state
  116. Transition transition;
  117. XsdParticleStateManager state;
  118. ArrayList occuredAtts = new ArrayList ();
  119. XsAttribute [] defaultAttributes = emptyAttributeArray;
  120. ArrayList defaultAttributesCache = new ArrayList ();
  121. #region ID Constraints
  122. XsdIDManager idManager = new XsdIDManager ();
  123. #endregion
  124. #region Key Constraints
  125. ArrayList keyTables = new ArrayList ();
  126. ArrayList currentKeyFieldConsumers = new ArrayList ();
  127. ArrayList tmpKeyrefPool;
  128. #endregion
  129. ArrayList elementQNameStack = new ArrayList ();
  130. StringBuilder storedCharacters = new StringBuilder ();
  131. bool shouldValidateCharacters;
  132. int depth;
  133. int xsiNilDepth = -1;
  134. int skipValidationDepth = -1;
  135. SOMObject currentType;
  136. #endregion
  137. #region Public properties
  138. // Settable Properties
  139. // IMHO It should just be an event that fires another event.
  140. public event ValidationEventHandler ValidationEventHandler;
  141. public object ValidationEventSender {
  142. get { return nominalEventSender; }
  143. set { nominalEventSender = value; }
  144. }
  145. // (kinda) Construction Properties
  146. public IXmlLineInfo LineInfoProvider {
  147. get { return lineInfo; }
  148. set { lineInfo = value; }
  149. }
  150. public XmlResolver XmlResolver {
  151. set { xmlResolver = value; }
  152. }
  153. [MonoTODO]
  154. public string SourceUri {
  155. get { return sourceUri; }
  156. // FIXME: actually there seems no setter, but then
  157. // it will never make sense.
  158. set { sourceUri = value; }
  159. }
  160. #endregion
  161. #region Private properties
  162. private XsdValidationContext Context {
  163. get { return state.Context; }
  164. }
  165. private bool IgnoreWarnings {
  166. get { return (options & ValidationFlags
  167. .IgnoreValidationWarnings) != 0; }
  168. }
  169. private bool IgnoreIdentity {
  170. get { return (options & ValidationFlags
  171. .IgnoreIdentityConstraints) != 0; }
  172. }
  173. #endregion
  174. #region Public methods
  175. // State Monitor
  176. public XmlSchemaAttribute [] GetExpectedAttributes ()
  177. {
  178. ArrayList al = new ArrayList ();
  179. ComplexType cType = Context.ActualType as ComplexType;
  180. if (cType == null)
  181. return emptyAttributeArray;
  182. foreach (DictionaryEntry entry in cType.AttributeUses)
  183. if (!occuredAtts.Contains ((QName) entry.Key))
  184. al.Add (entry.Value);
  185. return (XsAttribute [])
  186. al.ToArray (typeof (XsAttribute));
  187. }
  188. [MonoTODO]
  189. public XmlSchemaParticle [] GetExpectedParticles ()
  190. {
  191. throw new NotImplementedException ();
  192. }
  193. [MonoTODO ("check return type")]
  194. public void GetUnspecifiedDefaultAttributes (ArrayList list)
  195. {
  196. list.AddRange (defaultAttributes);
  197. }
  198. public object FindID (string name)
  199. {
  200. // It looks returning the element's local name (string)
  201. return idManager.FindID (name);
  202. }
  203. // State Controller
  204. public void Initialize ()
  205. {
  206. Initialize (null);
  207. }
  208. [MonoTODO]
  209. public void Initialize (SOMObject startType)
  210. {
  211. this.startType = startType;
  212. transition = Transition.Content;
  213. state = new XsdParticleStateManager ();
  214. if (!schemas.IsCompiled)
  215. schemas.Compile ();
  216. }
  217. // It must be called at the end of the validation (to check
  218. // identity constraints etc.).
  219. public void EndValidation ()
  220. {
  221. CheckState (Transition.Content);
  222. transition = Transition.Finished;
  223. if (schemas.Count == 0)
  224. return;
  225. if (depth > 0)
  226. throw new InvalidOperationException (String.Format ("There are {0} open element(s). ValidateEndElement() must be called for each open element.", depth));
  227. // 3.3.4 ElementLocallyValidElement 7 = Root Valid.
  228. if (!IgnoreIdentity &&
  229. idManager.HasMissingIDReferences ())
  230. HandleError ("There are missing ID references: " + idManager.GetMissingIDString ());
  231. }
  232. // I guess it is for validation error recovery
  233. [MonoTODO]
  234. public void SkipToEndElement (XmlSchemaInfo info)
  235. {
  236. CheckState (Transition.Content);
  237. if (schemas.Count == 0)
  238. return;
  239. throw new NotImplementedException ();
  240. }
  241. // I guess this weird XmlValueGetter is for such case that
  242. // value might not be required (and thus it improves
  243. // performance in some cases. Doh).
  244. // The return value is typed primitive, is possible.
  245. // AttDeriv
  246. public object ValidateAttribute (
  247. string localName,
  248. string ns,
  249. XmlValueGetter attributeValue,
  250. XmlSchemaInfo info)
  251. {
  252. CheckState (Transition.StartTag);
  253. if (ns == XmlNamespaceManager.XmlnsXmlns)
  254. return null;
  255. if (ns == XmlSchema.InstanceNamespace) {
  256. switch (localName) {
  257. case "schemaLocation":
  258. HandleSchemaLocation (attributeValue ());
  259. break;
  260. case "noNamespaceSchemaLocation":
  261. HandleNoNSSchemaLocation (attributeValue ());
  262. break;
  263. case "nil":
  264. HandleXsiNil (attributeValue, info);
  265. break;
  266. case "type":
  267. string xsiTypeName = attributeValue ();
  268. HandleXsiType (xsiTypeName.Trim (XmlChar.WhitespaceChars));
  269. break;
  270. default:
  271. HandleError ("Unknown schema instance namespace attribute: " + localName);
  272. break;
  273. }
  274. return null; // no further validation.
  275. }
  276. if (schemas.Count == 0)
  277. return null;
  278. occuredAtts.Add (new QName (localName, ns));
  279. // 3.3.4 Element Locally Valid (Type) - attribute
  280. if (Context.ActualType is ComplexType)
  281. return AssessAttributeElementLocallyValidType (localName, ns, attributeValue, info);
  282. else
  283. HandleError ("Current simple type cannot accept attributes other than schema instance namespace.");
  284. return null;
  285. }
  286. // StartTagOpenDeriv
  287. public void ValidateElement (
  288. string localName,
  289. string ns,
  290. XmlSchemaInfo info) // How is it used?
  291. {
  292. CheckState (Transition.Content);
  293. transition = Transition.StartTag;
  294. if (schemas.Count == 0)
  295. return;
  296. #region ID Constraints
  297. if (!IgnoreIdentity)
  298. idManager.OnStartElement ();
  299. #endregion
  300. defaultAttributes = emptyAttributeArray;
  301. elementQNameStack.Add (new XmlQualifiedName (localName, ns));
  302. // If there is no schema information, then no validation is performed.
  303. if (skipValidationDepth < 0 || depth <= skipValidationDepth) {
  304. if (shouldValidateCharacters)
  305. ValidateEndSimpleContent ();
  306. AssessOpenStartElementSchemaValidity (localName, ns);
  307. }
  308. shouldValidateCharacters = true;
  309. }
  310. public object ValidateEndElement (XmlSchemaInfo schemaInfo)
  311. {
  312. return ValidateEndElement (schemaInfo, null);
  313. }
  314. // The return value is typed primitive, is supplied.
  315. // EndTagDeriv
  316. [MonoTODO ("Find out what 'var' parameter means.")]
  317. public object ValidateEndElement (XmlSchemaInfo schemaInfo,
  318. object var)
  319. {
  320. CheckState (Transition.Content);
  321. if (schemas.Count == 0)
  322. return null;
  323. if (depth == 0)
  324. throw new InvalidOperationException ("There was no corresponding call to 'ValidateElement' method.");
  325. depth--;
  326. object ret = null;
  327. if (depth == skipValidationDepth)
  328. skipValidationDepth = -1;
  329. else if (skipValidationDepth < 0 || depth <= skipValidationDepth)
  330. ret = AssessEndElementSchemaValidity ();
  331. elementQNameStack.RemoveAt (elementQNameStack.Count - 1);
  332. return ret;
  333. }
  334. // StartTagCloseDeriv
  335. public void ValidateEndOfAttributes ()
  336. {
  337. CheckState (Transition.StartTag);
  338. transition = Transition.Content;
  339. if (schemas.Count == 0)
  340. return;
  341. AssessCloseStartElementSchemaValidity ();
  342. }
  343. // TextDeriv ... without text. Maybe typed check is done by
  344. // ValidateAtomicValue().
  345. public void ValidateText (XmlValueGetter getter)
  346. {
  347. CheckState (Transition.Content);
  348. if (schemas.Count == 0)
  349. return;
  350. ComplexType ct = Context.ActualType as ComplexType;
  351. if (ct != null && storedCharacters.Length > 0) {
  352. switch (ct.ContentType) {
  353. case XmlSchemaContentType.ElementOnly:
  354. case XmlSchemaContentType.Empty:
  355. HandleError ("Not allowed character content was found.");
  356. break;
  357. }
  358. }
  359. ValidateCharacters (getter);
  360. }
  361. // TextDeriv...?
  362. [MonoTODO]
  363. public void ValidateWhitespace (XmlValueGetter getter)
  364. {
  365. CheckState (Transition.Content);
  366. if (schemas.Count == 0)
  367. return;
  368. // throw new NotImplementedException ();
  369. }
  370. #endregion
  371. #region Error handling
  372. private void HandleError (string message)
  373. {
  374. HandleError (message, null, false);
  375. }
  376. private void HandleError (
  377. string message, Exception innerException)
  378. {
  379. HandleError (message, innerException, false);
  380. }
  381. private void HandleError (string message,
  382. Exception innerException, bool isWarning)
  383. {
  384. if (isWarning && IgnoreWarnings)
  385. return;
  386. ValException vex = new ValException (
  387. message, nominalEventSender, SourceUri,
  388. null, innerException);
  389. HandleError (vex, isWarning);
  390. }
  391. private void HandleError (ValException exception)
  392. {
  393. HandleError (exception, false);
  394. }
  395. private void HandleError (ValException exception, bool isWarning)
  396. {
  397. if (isWarning && IgnoreWarnings)
  398. return;
  399. if (ValidationEventHandler == null)
  400. throw exception;
  401. ValidationEventArgs e = new ValidationEventArgs (
  402. exception,
  403. exception.Message,
  404. isWarning ? XmlSeverityType.Warning :
  405. XmlSeverityType.Error);
  406. ValidationEventHandler (nominalEventSender, e);
  407. }
  408. #endregion
  409. #region External schema resolution
  410. private XmlSchema ReadExternalSchema (string uri)
  411. {
  412. Uri absUri = xmlResolver.ResolveUri ((SourceUri != "" ? new Uri (SourceUri) : null), uri);
  413. XmlTextReader xtr = null;
  414. try {
  415. xtr = new XmlTextReader (absUri.ToString (),
  416. (Stream) xmlResolver.GetEntity (
  417. absUri, null, typeof (Stream)),
  418. nameTable);
  419. return XmlSchema.Read (
  420. xtr, ValidationEventHandler);
  421. } finally {
  422. if (xtr != null)
  423. xtr.Close ();
  424. }
  425. }
  426. private void HandleSchemaLocation (string schemaLocation)
  427. {
  428. if (xmlResolver == null)
  429. return;
  430. XmlSchema schema = null;
  431. bool schemaAdded = false;
  432. string [] tmp = null;
  433. try {
  434. schemaLocation = XsDatatype.FromName ("token", XmlSchema.Namespace).Normalize (schemaLocation);
  435. tmp = schemaLocation.Split (XmlChar.WhitespaceChars);
  436. } catch (Exception ex) {
  437. HandleError ("Invalid schemaLocation attribute format.", ex, true);
  438. tmp = new string [0];
  439. }
  440. if (tmp.Length % 2 != 0)
  441. HandleError ("Invalid schemaLocation attribute format.");
  442. for (int i = 0; i < tmp.Length; i += 2) {
  443. try {
  444. schema = ReadExternalSchema (tmp [i + 1]);
  445. } catch (Exception) { // FIXME: (wishlist) It is bad manner ;-(
  446. HandleError ("Could not resolve schema location URI: " + schemaLocation, null, true);
  447. continue;
  448. }
  449. if (schema.TargetNamespace == null)
  450. schema.TargetNamespace = tmp [i];
  451. else if (schema.TargetNamespace != tmp [i])
  452. HandleError ("Specified schema has different target namespace.");
  453. if (schema != null) {
  454. if (!schemas.Contains (schema.TargetNamespace)) {
  455. schemaAdded = true;
  456. schemas.Add (schema);
  457. }
  458. }
  459. }
  460. // FIXME: should call Reprocess()?
  461. if (schemaAdded)
  462. schemas.Compile ();
  463. }
  464. private void HandleNoNSSchemaLocation (string noNsSchemaLocation)
  465. {
  466. if (xmlResolver == null)
  467. return;
  468. XmlSchema schema = null;
  469. bool schemaAdded = false;
  470. Uri absUri = null;
  471. XmlTextReader xtr = null;
  472. try {
  473. schema = ReadExternalSchema (noNsSchemaLocation);
  474. } catch (Exception) { // FIXME: (wishlist) It is bad manner ;-(
  475. HandleError ("Could not resolve schema location URI: " + noNsSchemaLocation, null, true);
  476. } finally {
  477. if (xtr != null)
  478. xtr.Close ();
  479. }
  480. if (schema != null && schema.TargetNamespace != null)
  481. HandleError ("Specified schema has different target namespace.");
  482. if (schema != null) {
  483. if (!schemas.Contains (schema.TargetNamespace)) {
  484. schemaAdded = true;
  485. schemas.Add (schema);
  486. }
  487. }
  488. // FIXME: should call Reprocess()?
  489. if (schemaAdded)
  490. schemas.Compile ();
  491. }
  492. #endregion
  493. private void CheckState (Transition expected)
  494. {
  495. if (transition != expected) {
  496. if (transition == Transition.None)
  497. throw new InvalidOperationException ("Initialize() must be called before processing validation.");
  498. else
  499. throw new InvalidOperationException (
  500. String.Format ("Unexpected attempt to validation state transition from {0} to {1} was happened.",
  501. transition,
  502. expected));
  503. }
  504. }
  505. private XsElement FindElement (string name, string ns)
  506. {
  507. return (XsElement) schemas.GlobalElements [new XmlQualifiedName (name, ns)];
  508. }
  509. private XmlSchemaType FindType (XmlQualifiedName qname)
  510. {
  511. return (XmlSchemaType) schemas.GlobalTypes [qname];
  512. }
  513. #region Type Validation
  514. private void ValidateStartElementParticle (
  515. string localName, string ns)
  516. {
  517. if (Context.State == null)
  518. return;
  519. Context.XsiType = null;
  520. state.CurrentElement = null;
  521. Context.EvaluateStartElement (localName,
  522. ns);
  523. if (Context.IsInvalid)
  524. HandleError ("Invalid start element: " + ns + ":" + localName);
  525. Context.SetElement (state.CurrentElement);
  526. }
  527. private void AssessOpenStartElementSchemaValidity (
  528. string localName, string ns)
  529. {
  530. // If the reader is inside xsi:nil (and failed
  531. // on validation), then simply skip its content.
  532. if (xsiNilDepth >= 0 && xsiNilDepth < depth)
  533. HandleError ("Element item appeared, while current element context is nil.");
  534. ValidateStartElementParticle (localName, ns);
  535. // Create Validation Root, if not exist.
  536. // [Schema Validity Assessment (Element) 1.1]
  537. if (Context.Element == null) {
  538. state.CurrentElement = FindElement (localName, ns);
  539. Context.SetElement (state.CurrentElement);
  540. }
  541. #region Key Constraints
  542. if (!IgnoreIdentity)
  543. ValidateKeySelectors ();
  544. ValidateKeyFields (false, xsiNilDepth == depth,
  545. Context.ActualType, null, null, null);
  546. #endregion
  547. }
  548. private void AssessCloseStartElementSchemaValidity ()
  549. {
  550. if (Context.XsiType != null)
  551. AssessCloseStartElementLocallyValidType ();
  552. else if (Context.Element != null) {
  553. // element locally valid is checked only when
  554. // xsi:type does not exist.
  555. AssessElementLocallyValidElement ();
  556. if (Context.Element.ElementType != null)
  557. AssessCloseStartElementLocallyValidType ();
  558. }
  559. if (Context.Element == null) {
  560. switch (state.ProcessContents) {
  561. case ContentProc.Skip:
  562. break;
  563. case ContentProc.Lax:
  564. break;
  565. default:
  566. QName current = (QName) elementQNameStack [elementQNameStack.Count - 1];
  567. if (Context.XsiType == null &&
  568. (schemas.Contains (current.Namespace) ||
  569. !schemas.MissedSubComponents (current.Namespace)))
  570. HandleError ("Element declaration for " + current + " is missing.");
  571. break;
  572. }
  573. }
  574. // Proceed to the next depth.
  575. state.PushContext ();
  576. XsdValidationState next = null;
  577. if (state.ProcessContents == ContentProc.Skip)
  578. skipValidationDepth = depth;
  579. else {
  580. // create child particle state.
  581. ComplexType xsComplexType = Context.ActualType as ComplexType;
  582. if (xsComplexType != null)
  583. next = state.Create (xsComplexType.ValidatableParticle);
  584. else if (state.ProcessContents == ContentProc.Lax)
  585. next = state.Create (XmlSchemaAny.AnyTypeContent);
  586. else
  587. next = state.Create (XmlSchemaParticle.Empty);
  588. }
  589. Context.State = next;
  590. depth++;
  591. }
  592. // It must be invoked after xsi:nil turned out not to be in
  593. // this element.
  594. private void AssessElementLocallyValidElement ()
  595. {
  596. XsElement element = Context.Element;
  597. XmlQualifiedName qname = (XmlQualifiedName) elementQNameStack [elementQNameStack.Count - 1];
  598. // 1.
  599. if (element == null)
  600. HandleError ("Element declaration is required for " + qname);
  601. // 2.
  602. if (element.ActualIsAbstract)
  603. HandleError ("Abstract element declaration was specified for " + qname);
  604. // 3. is checked inside ValidateAttribute().
  605. }
  606. // 3.3.4 Element Locally Valid (Type)
  607. private void AssessCloseStartElementLocallyValidType ()
  608. {
  609. object schemaType = Context.ActualType;
  610. if (schemaType == null) { // 1.
  611. HandleError ("Schema type does not exist.");
  612. return;
  613. }
  614. ComplexType cType = schemaType as ComplexType;
  615. SimpleType sType = schemaType as SimpleType;
  616. if (sType != null) {
  617. // 3.1.1.
  618. // Attributes are checked in ValidateAttribute().
  619. } else if (cType != null) {
  620. // 3.2. Also, 2. is checked there.
  621. AssessCloseStartElementLocallyValidComplexType (cType);
  622. }
  623. }
  624. // 3.4.4 Element Locally Valid (Complex Type)
  625. private void AssessCloseStartElementLocallyValidComplexType (ComplexType cType)
  626. {
  627. // 1.
  628. if (cType.IsAbstract) {
  629. HandleError ("Target complex type is abstract.");
  630. return;
  631. }
  632. // 2 (xsi:nil and content prohibition)
  633. // See AssessStartElementSchemaValidity() and ValidateCharacters()
  634. // 3. attribute uses and 5. wild IDs are handled at
  635. // ValidateAttribute().
  636. // Collect default attributes.
  637. // 4.
  638. foreach (XsAttribute attr in GetExpectedAttributes ()) {
  639. if (attr.ValidatedUse == XmlSchemaUse.Required &&
  640. attr.ValidatedFixedValue == null)
  641. HandleError ("Required attribute " + attr.QualifiedName + " was not found.");
  642. else if (attr.ValidatedDefaultValue != null || attr.ValidatedFixedValue != null)
  643. defaultAttributesCache.Add (attr);
  644. }
  645. if (defaultAttributesCache.Count == 0)
  646. defaultAttributes = emptyAttributeArray;
  647. else
  648. defaultAttributes = (XsAttribute [])
  649. defaultAttributesCache.ToArray (
  650. typeof (XsAttribute));
  651. defaultAttributesCache.Clear ();
  652. // 5. wild IDs was already checked at ValidateAttribute().
  653. occuredAtts.Clear ();
  654. }
  655. private object AssessAttributeElementLocallyValidType (string localName, string ns, XmlValueGetter getter, XmlSchemaInfo info)
  656. {
  657. ComplexType cType = Context.ActualType as ComplexType;
  658. XmlQualifiedName qname = new XmlQualifiedName (localName, ns);
  659. // including 3.10.4 Item Valid (Wildcard)
  660. XmlSchemaObject attMatch = XmlSchemaUtil.FindAttributeDeclaration (ns, schemas, cType, qname);
  661. if (attMatch == null)
  662. HandleError ("Attribute declaration was not found for " + qname);
  663. XsAttribute attdecl = attMatch as XsAttribute;
  664. if (attdecl != null) {
  665. AssessAttributeLocallyValidUse (attdecl);
  666. return AssessAttributeLocallyValid (attdecl, getter);
  667. } // otherwise anyAttribute or null.
  668. return null;
  669. }
  670. // 3.2.4 Attribute Locally Valid and 3.4.4
  671. private object AssessAttributeLocallyValid (XsAttribute attr, XmlValueGetter getter)
  672. {
  673. // 2. - 4.
  674. if (attr.AttributeType == null)
  675. HandleError ("Attribute type is missing for " + attr.QualifiedName);
  676. XsDatatype dt = attr.AttributeType as XsDatatype;
  677. if (dt == null)
  678. dt = ((SimpleType) attr.AttributeType).Datatype;
  679. // It is a bit heavy process, so let's omit as long as possible ;-)
  680. if (dt != SimpleType.AnySimpleType || attr.ValidatedFixedValue != null) {
  681. string normalized = dt.Normalize (getter ());
  682. object parsedValue = null;
  683. try {
  684. parsedValue = dt.ParseValue (normalized, nameTable, nsResolver);
  685. } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
  686. HandleError ("Attribute value is invalid against its data type " + dt.TokenizedType, ex);
  687. }
  688. if (attr.ValidatedFixedValue != null && attr.ValidatedFixedValue != normalized) {
  689. HandleError ("The value of the attribute " + attr.QualifiedName + " does not match with its fixed value.");
  690. parsedValue = dt.ParseValue (attr.ValidatedFixedValue, nameTable, nsResolver);
  691. }
  692. #region ID Constraints
  693. if (!IgnoreIdentity) {
  694. string error = idManager.AssessEachAttributeIdentityConstraint (dt, parsedValue, ((QName) elementQNameStack [elementQNameStack.Count - 1]).Name);
  695. if (error != null)
  696. HandleError (error);
  697. }
  698. #endregion
  699. #region Key Constraints
  700. if (!IgnoreIdentity)
  701. ValidateKeyFields (
  702. true,
  703. false,
  704. attr.AttributeType,
  705. attr.QualifiedName.Name,
  706. attr.QualifiedName.Namespace,
  707. getter);
  708. #endregion
  709. return parsedValue;
  710. }
  711. return null;
  712. }
  713. private void AssessAttributeLocallyValidUse (XsAttribute attr)
  714. {
  715. // This is extra check than spec 3.5.4
  716. if (attr.ValidatedUse == XmlSchemaUse.Prohibited)
  717. HandleError ("Attribute " + attr.QualifiedName + " is prohibited in this context.");
  718. }
  719. private object AssessEndElementSchemaValidity ()
  720. {
  721. ValidateEndElementParticle (); // validate against childrens' state.
  722. object ret = ValidateEndSimpleContent ();
  723. // 3.3.4 Assess ElementLocallyValidElement 5: value constraints.
  724. // 3.3.4 Assess ElementLocallyValidType 3.1.3. = StringValid(3.14.4)
  725. // => ValidateEndSimpleContent ().
  726. #region Key Constraints
  727. if (!IgnoreIdentity)
  728. ValidateEndElementKeyConstraints ();
  729. #endregion
  730. // Reset xsi:nil, if required.
  731. if (xsiNilDepth == depth)
  732. xsiNilDepth = -1;
  733. return ret;
  734. }
  735. private void ValidateEndElementParticle ()
  736. {
  737. if (Context.State != null) {
  738. if (!Context.EvaluateEndElement ()) {
  739. HandleError ("Invalid end element. There are still required content items.");
  740. }
  741. }
  742. state.PopContext ();
  743. }
  744. // Utility for missing validation completion related to child items.
  745. private void ValidateCharacters (XmlValueGetter getter)
  746. {
  747. if (xsiNilDepth >= 0 && xsiNilDepth < depth)
  748. HandleError ("Element item appeared, while current element context is nil.");
  749. if (shouldValidateCharacters)
  750. storedCharacters.Append (getter ());
  751. }
  752. // Utility for missing validation completion related to child items.
  753. private object ValidateEndSimpleContent ()
  754. {
  755. object ret = null;
  756. if (shouldValidateCharacters)
  757. ret = ValidateEndSimpleContentCore ();
  758. shouldValidateCharacters = false;
  759. storedCharacters.Length = 0;
  760. return ret;
  761. }
  762. private object ValidateEndSimpleContentCore ()
  763. {
  764. if (Context.ActualType == null)
  765. return null;
  766. string value = storedCharacters.ToString ();
  767. object ret = null;
  768. if (value.Length == 0) {
  769. // 3.3.4 Element Locally Valid (Element) 5.1.2
  770. if (Context.Element != null) {
  771. if (Context.Element.ValidatedDefaultValue != null)
  772. value = Context.Element.ValidatedDefaultValue;
  773. }
  774. }
  775. XsDatatype dt = Context.ActualType as XsDatatype;
  776. SimpleType st = Context.ActualType as SimpleType;
  777. if (dt == null) {
  778. if (st != null) {
  779. dt = st.Datatype;
  780. } else {
  781. ComplexType ct = Context.ActualType as ComplexType;
  782. dt = ct.Datatype;
  783. switch (ct.ContentType) {
  784. case XmlSchemaContentType.ElementOnly:
  785. case XmlSchemaContentType.Empty:
  786. if (value.Length > 0)
  787. HandleError ("Character content not allowed.");
  788. break;
  789. }
  790. }
  791. }
  792. if (dt != null) {
  793. // 3.3.4 Element Locally Valid (Element) :: 5.2.2.2. Fixed value constraints
  794. if (Context.Element != null && Context.Element.ValidatedFixedValue != null)
  795. if (value != Context.Element.ValidatedFixedValue)
  796. HandleError ("Fixed value constraint was not satisfied.");
  797. ret = AssessStringValid (st, dt, value);
  798. }
  799. #region Key Constraints
  800. if (!IgnoreIdentity)
  801. ValidateSimpleContentIdentity (dt, value);
  802. #endregion
  803. shouldValidateCharacters = false;
  804. return ret;
  805. }
  806. // 3.14.4 String Valid
  807. private object AssessStringValid (SimpleType st,
  808. XsDatatype dt, string value)
  809. {
  810. XsDatatype validatedDatatype = dt;
  811. object ret = null;
  812. if (st != null) {
  813. string normalized = validatedDatatype.Normalize (value);
  814. string [] values;
  815. XsDatatype itemDatatype;
  816. SimpleType itemSimpleType;
  817. switch (st.DerivedBy) {
  818. case XmlSchemaDerivationMethod.List:
  819. SimpleTypeList listContent = st.Content as SimpleTypeList;
  820. values = normalized.Split (XmlChar.WhitespaceChars);
  821. // LAMESPEC: Types of each element in
  822. // the returned list might be
  823. // inconsistent, so basically returning
  824. // value does not make sense without
  825. // explicit runtime type information
  826. // for base primitive type.
  827. object [] retValues = new object [values.Length];
  828. itemDatatype = listContent.ValidatedListItemType as XsDatatype;
  829. itemSimpleType = listContent.ValidatedListItemType as SimpleType;
  830. for (int vi = 0; vi < values.Length; vi++) {
  831. string each = values [vi];
  832. if (each == String.Empty)
  833. continue;
  834. // validate against ValidatedItemType
  835. if (itemDatatype != null) {
  836. try {
  837. retValues [vi] = itemDatatype.ParseValue (each, nameTable, nsResolver);
  838. } catch (Exception ex) { // FIXME: (wishlist) better exception handling ;-(
  839. HandleError ("List type value contains one or more invalid values.", ex);
  840. break;
  841. }
  842. }
  843. else
  844. AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
  845. }
  846. ret = retValues;
  847. break;
  848. case XmlSchemaDerivationMethod.Union:
  849. SimpleTypeUnion union = st.Content as SimpleTypeUnion;
  850. {
  851. string each = normalized;
  852. // validate against ValidatedItemType
  853. bool passed = false;
  854. foreach (object eachType in union.ValidatedTypes) {
  855. itemDatatype = eachType as XsDatatype;
  856. itemSimpleType = eachType as SimpleType;
  857. if (itemDatatype != null) {
  858. try {
  859. ret = itemDatatype.ParseValue (each, nameTable, nsResolver);
  860. } catch (Exception) { // FIXME: (wishlist) better exception handling ;-(
  861. continue;
  862. }
  863. }
  864. else {
  865. try {
  866. ret = AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
  867. } catch (ValException) {
  868. continue;
  869. }
  870. }
  871. passed = true;
  872. break;
  873. }
  874. if (!passed) {
  875. HandleError ("Union type value contains one or more invalid values.");
  876. break;
  877. }
  878. }
  879. break;
  880. case XmlSchemaDerivationMethod.Restriction:
  881. SimpleTypeRest str = st.Content as SimpleTypeRest;
  882. // facet validation
  883. if (str != null) {
  884. /* Don't forget to validate against inherited type's facets
  885. * Could we simplify this by assuming that the basetype will also
  886. * be restriction?
  887. * */
  888. // mmm, will check later.
  889. SimpleType baseType = st.BaseXmlSchemaType as SimpleType;
  890. if (baseType != null) {
  891. ret = AssessStringValid (baseType, dt, normalized);
  892. }
  893. if (!str.ValidateValueWithFacets (normalized, nameTable)) {
  894. HandleError ("Specified value was invalid against the facets.");
  895. break;
  896. }
  897. }
  898. validatedDatatype = st.Datatype;
  899. break;
  900. }
  901. }
  902. if (validatedDatatype != null) {
  903. try {
  904. ret = validatedDatatype.ParseValue (value, nameTable, nsResolver);
  905. } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
  906. HandleError (String.Format ("Invalidly typed data was specified."), ex);
  907. }
  908. }
  909. return ret;
  910. }
  911. #endregion
  912. #region Key Constraints Validation
  913. private XsdKeyTable CreateNewKeyTable (XmlSchemaIdentityConstraint ident)
  914. {
  915. XsdKeyTable seq = new XsdKeyTable (ident);
  916. seq.StartDepth = depth;
  917. this.keyTables.Add (seq);
  918. return seq;
  919. }
  920. // 3.11.4 Identity Constraint Satisfied
  921. private void ValidateKeySelectors ()
  922. {
  923. if (tmpKeyrefPool != null)
  924. tmpKeyrefPool.Clear ();
  925. if (Context.Element != null && Context.Element.Constraints.Count > 0) {
  926. // (a) Create new key sequences, if required.
  927. for (int i = 0; i < Context.Element.Constraints.Count; i++) {
  928. XmlSchemaIdentityConstraint ident = (XmlSchemaIdentityConstraint) Context.Element.Constraints [i];
  929. XsdKeyTable seq = CreateNewKeyTable (ident);
  930. if (ident is XmlSchemaKeyref) {
  931. if (tmpKeyrefPool == null)
  932. tmpKeyrefPool = new ArrayList ();
  933. tmpKeyrefPool.Add (seq);
  934. }
  935. }
  936. }
  937. // (b) Evaluate current key sequences.
  938. for (int i = 0; i < keyTables.Count; i++) {
  939. XsdKeyTable seq = (XsdKeyTable) keyTables [i];
  940. if (seq.SelectorMatches (this.elementQNameStack, depth) != null) {
  941. // creates and registers new entry.
  942. XsdKeyEntry entry = new XsdKeyEntry (seq, depth, lineInfo);
  943. seq.Entries.Add (entry);
  944. }
  945. }
  946. }
  947. private void ValidateKeyFields (bool isAttr, bool isNil, object schemaType, string attrName, string attrNs, XmlValueGetter getter)
  948. {
  949. // (c) Evaluate field paths.
  950. for (int i = 0; i < keyTables.Count; i++) {
  951. XsdKeyTable seq = (XsdKeyTable) keyTables [i];
  952. // If possible, create new field entry candidates.
  953. for (int j = 0; j < seq.Entries.Count; j++) {
  954. try {
  955. seq.Entries [j].ProcessMatch (
  956. isAttr,
  957. elementQNameStack,
  958. nominalEventSender,
  959. nameTable,
  960. SourceUri,
  961. schemaType,
  962. nsResolver,
  963. lineInfo,
  964. depth,
  965. attrName,
  966. attrNs,
  967. getter == null ?
  968. null :
  969. getter (),
  970. isNil,
  971. currentKeyFieldConsumers);
  972. } catch (ValException ex) {
  973. HandleError (ex);
  974. }
  975. }
  976. }
  977. }
  978. private void ProcessKeyEntryOne (XsdKeyEntry entry, bool isAttr, bool isNil, object schemaType, string attrName, string attrNs, XmlValueGetter getter)
  979. {
  980. }
  981. private void ValidateEndElementKeyConstraints ()
  982. {
  983. // Reset Identity constraints.
  984. for (int i = 0; i < keyTables.Count; i++) {
  985. XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
  986. if (seq.StartDepth == depth) {
  987. ValidateEndKeyConstraint (seq);
  988. } else {
  989. for (int k = 0; k < seq.Entries.Count; k++) {
  990. XsdKeyEntry entry = seq.Entries [k] as XsdKeyEntry;
  991. // Remove finished (maybe key not found) entries.
  992. if (entry.StartDepth == depth) {
  993. if (entry.KeyFound)
  994. seq.FinishedEntries.Add (entry);
  995. else if (seq.SourceSchemaIdentity is XmlSchemaKey)
  996. HandleError ("Key sequence is missing.");
  997. seq.Entries.RemoveAt (k);
  998. k--;
  999. }
  1000. // Pop validated key depth to find two or more fields.
  1001. else {
  1002. for (int j = 0; j < entry.KeyFields.Count; j++) {
  1003. XsdKeyEntryField kf = entry.KeyFields [j];
  1004. if (!kf.FieldFound && kf.FieldFoundDepth == depth) {
  1005. kf.FieldFoundDepth = 0;
  1006. kf.FieldFoundPath = null;
  1007. }
  1008. }
  1009. }
  1010. }
  1011. }
  1012. }
  1013. for (int i = 0; i < keyTables.Count; i++) {
  1014. XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
  1015. if (seq.StartDepth == depth) {
  1016. keyTables.RemoveAt (i);
  1017. i--;
  1018. }
  1019. }
  1020. }
  1021. private void ValidateEndKeyConstraint (XsdKeyTable seq)
  1022. {
  1023. ArrayList errors = new ArrayList ();
  1024. for (int i = 0; i < seq.Entries.Count; i++) {
  1025. XsdKeyEntry entry = (XsdKeyEntry) seq.Entries [i];
  1026. if (entry.KeyFound)
  1027. continue;
  1028. if (seq.SourceSchemaIdentity is XmlSchemaKey)
  1029. errors.Add ("line " + entry.SelectorLineNumber + "position " + entry.SelectorLinePosition);
  1030. }
  1031. if (errors.Count > 0)
  1032. HandleError ("Invalid identity constraints were found. Key was not found. "
  1033. + String.Join (", ", errors.ToArray (typeof (string)) as string []));
  1034. errors.Clear ();
  1035. // Find reference target
  1036. XmlSchemaKeyref xsdKeyref = seq.SourceSchemaIdentity as XmlSchemaKeyref;
  1037. if (xsdKeyref != null) {
  1038. for (int i = this.keyTables.Count - 1; i >= 0; i--) {
  1039. XsdKeyTable target = this.keyTables [i] as XsdKeyTable;
  1040. if (target.SourceSchemaIdentity == xsdKeyref.Target) {
  1041. seq.ReferencedKey = target;
  1042. for (int j = 0; j < seq.FinishedEntries.Count; j++) {
  1043. XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [j];
  1044. for (int k = 0; k < target.FinishedEntries.Count; k++) {
  1045. XsdKeyEntry targetEntry = (XsdKeyEntry) target.FinishedEntries [k];
  1046. if (entry.CompareIdentity (targetEntry)) {
  1047. entry.KeyRefFound = true;
  1048. break;
  1049. }
  1050. }
  1051. }
  1052. }
  1053. }
  1054. if (seq.ReferencedKey == null)
  1055. HandleError ("Target key was not found.");
  1056. for (int i = 0; i < seq.FinishedEntries.Count; i++) {
  1057. XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [i];
  1058. if (!entry.KeyRefFound)
  1059. errors.Add (" line " + entry.SelectorLineNumber + ", position " + entry.SelectorLinePosition);
  1060. }
  1061. if (errors.Count > 0)
  1062. HandleError ("Invalid identity constraints were found. Referenced key was not found: "
  1063. + String.Join (" / ", errors.ToArray (typeof (string)) as string []));
  1064. }
  1065. }
  1066. private void ValidateSimpleContentIdentity (
  1067. XmlSchemaDatatype dt, string value)
  1068. {
  1069. // Identity field value
  1070. if (currentKeyFieldConsumers != null) {
  1071. while (this.currentKeyFieldConsumers.Count > 0) {
  1072. XsdKeyEntryField field = this.currentKeyFieldConsumers [0] as XsdKeyEntryField;
  1073. if (field.Identity != null)
  1074. HandleError ("Two or more identical field was found. Former value is '" + field.Identity + "' .");
  1075. object identity = null; // This means empty value
  1076. if (dt != null) {
  1077. try {
  1078. identity = dt.ParseValue (value, nameTable, nsResolver);
  1079. } catch (Exception ex) { // FIXME: (wishlist) This is bad manner ;-(
  1080. HandleError ("Identity value is invalid against its data type " + dt.TokenizedType, ex);
  1081. }
  1082. }
  1083. if (identity == null)
  1084. identity = value;
  1085. if (!field.SetIdentityField (identity, depth == xsiNilDepth, dt as XsdAnySimpleType, depth, lineInfo))
  1086. HandleError ("Two or more identical key value was found: '" + value + "' .");
  1087. this.currentKeyFieldConsumers.RemoveAt (0);
  1088. }
  1089. }
  1090. }
  1091. #endregion
  1092. #region xsi:type
  1093. private object GetXsiType (string name)
  1094. {
  1095. object xsiType = null;
  1096. XmlQualifiedName typeQName =
  1097. XmlQualifiedName.Parse (name, nsResolver);
  1098. if (typeQName == ComplexType.AnyTypeName)
  1099. xsiType = ComplexType.AnyType;
  1100. else if (XmlSchemaUtil.IsBuiltInDatatypeName (typeQName))
  1101. xsiType = XsDatatype.FromName (typeQName);
  1102. else
  1103. xsiType = FindType (typeQName);
  1104. return xsiType;
  1105. }
  1106. private void HandleXsiType (string typename)
  1107. {
  1108. XsElement element = Context.Element;
  1109. object xsiType = GetXsiType (typename);
  1110. if (xsiType == null) {
  1111. HandleError ("The instance type was not found: " + typename);
  1112. return;
  1113. }
  1114. XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
  1115. if (xsiSchemaType != null && Context.Element != null) {
  1116. XmlSchemaType elemBaseType = element.ElementType as XmlSchemaType;
  1117. if (elemBaseType != null && (xsiSchemaType.DerivedBy & elemBaseType.FinalResolved) != 0)
  1118. HandleError ("The instance type is prohibited by the type of the context element.");
  1119. if (elemBaseType != xsiType && (xsiSchemaType.DerivedBy & element.BlockResolved) != 0)
  1120. HandleError ("The instance type is prohibited by the context element.");
  1121. }
  1122. ComplexType xsiComplexType = xsiType as ComplexType;
  1123. if (xsiComplexType != null && xsiComplexType.IsAbstract)
  1124. HandleError ("The instance type is abstract: " + typename);
  1125. else {
  1126. // If current schema type exists, then this xsi:type must be
  1127. // valid extension of that type. See 1.2.1.2.4.
  1128. if (element != null) {
  1129. AssessLocalTypeDerivationOK (xsiType, element.ElementType, element.BlockResolved);
  1130. }
  1131. // See also ValidateEndOfAttributes().
  1132. Context.XsiType = xsiType;
  1133. }
  1134. }
  1135. // It is common to ElementLocallyValid::4 and SchemaValidityAssessment::1.2.1.2.4
  1136. private void AssessLocalTypeDerivationOK (object xsiType, object baseType, XmlSchemaDerivationMethod flag)
  1137. {
  1138. XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
  1139. ComplexType baseComplexType = baseType as ComplexType;
  1140. ComplexType xsiComplexType = xsiSchemaType as ComplexType;
  1141. if (xsiType != baseType) {
  1142. // Extracted (not extraneous) check for 3.4.6 TypeDerivationOK.
  1143. if (baseComplexType != null)
  1144. flag |= baseComplexType.BlockResolved;
  1145. if (flag == XmlSchemaDerivationMethod.All) {
  1146. HandleError ("Prohibited element type substitution.");
  1147. return;
  1148. } else if (xsiSchemaType != null && (flag & xsiSchemaType.DerivedBy) != 0) {
  1149. HandleError ("Prohibited element type substitution.");
  1150. return;
  1151. }
  1152. }
  1153. if (xsiComplexType != null)
  1154. try {
  1155. xsiComplexType.ValidateTypeDerivationOK (baseType, null, null);
  1156. } catch (ValException ex) {
  1157. HandleError (ex);
  1158. }
  1159. else {
  1160. SimpleType xsiSimpleType = xsiType as SimpleType;
  1161. if (xsiSimpleType != null) {
  1162. try {
  1163. xsiSimpleType.ValidateTypeDerivationOK (baseType, null, null, true);
  1164. } catch (ValException ex) {
  1165. HandleError (ex);
  1166. }
  1167. }
  1168. else if (xsiType is XsDatatype) {
  1169. // do nothing
  1170. }
  1171. else
  1172. HandleError ("Primitive data type cannot be derived type using xsi:type specification.");
  1173. }
  1174. }
  1175. #endregion
  1176. private void HandleXsiNil (XmlValueGetter getter, XmlSchemaInfo info)
  1177. {
  1178. XsElement element = Context.Element;
  1179. if (!element.ActualIsNillable) {
  1180. HandleError (String.Format ("Current element '{0}' is not nillable and thus does not allow occurence of 'nil' attribute.", Context.Element.QualifiedName));
  1181. return;
  1182. }
  1183. string value = getter ().Trim (XmlChar.WhitespaceChars);
  1184. // 3.2.
  1185. // Note that 3.2.1 xsi:nil constraints are to be
  1186. // validated in AssessElementSchemaValidity() and
  1187. // ValidateCharacters().
  1188. if (value == "true") {
  1189. if (element.ValidatedFixedValue != null)
  1190. HandleError ("Schema instance nil was specified, where the element declaration for " + element.QualifiedName + "has fixed value constraints.");
  1191. xsiNilDepth = depth;
  1192. if (info != null)
  1193. info.IsNil = true;
  1194. }
  1195. }
  1196. }
  1197. }
  1198. #endif