XmlSchemaValidator.cs 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443
  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 sealed 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. Uri 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. public Uri SourceUri {
  154. get { return sourceUri; }
  155. set { sourceUri = value; }
  156. }
  157. #endregion
  158. #region Private properties
  159. private string BaseUri {
  160. get { return sourceUri != null ? sourceUri.AbsoluteUri : String.Empty; }
  161. }
  162. private XsdValidationContext Context {
  163. get { return state.Context; }
  164. }
  165. private bool IgnoreWarnings {
  166. get { return (options & ValidationFlags
  167. .ReportValidationWarnings) == 0; }
  168. }
  169. private bool IgnoreIdentity {
  170. get { return (options & ValidationFlags
  171. .ProcessIdentityConstraints) == 0; }
  172. }
  173. #endregion
  174. #region Public methods
  175. // State Monitor
  176. public XmlSchemaAttribute [] GetExpectedAttributes ()
  177. {
  178. ComplexType cType = Context.ActualType as ComplexType;
  179. if (cType == null)
  180. return emptyAttributeArray;
  181. ArrayList al = new ArrayList ();
  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. private void CollectAtomicParticles (XmlSchemaParticle p,
  189. ArrayList al)
  190. {
  191. if (p is XmlSchemaGroupBase) {
  192. foreach (XmlSchemaParticle c in
  193. ((XmlSchemaGroupBase) p).Items)
  194. CollectAtomicParticles (c, al);
  195. }
  196. else
  197. al.Add (p);
  198. }
  199. [MonoTODO ("Need some tests.")]
  200. // Its behavior is not obvious. For example, it does not
  201. // contain groups (xs:sequence/xs:choice/xs:all). Since it
  202. // might contain xs:any, it could not be of type element[].
  203. public XmlSchemaParticle [] GetExpectedParticles ()
  204. {
  205. ArrayList al = new ArrayList ();
  206. Context.State.GetExpectedParticles (al);
  207. ArrayList ret = new ArrayList ();
  208. foreach (XmlSchemaParticle p in al)
  209. CollectAtomicParticles (p, ret);
  210. return (XmlSchemaParticle []) ret.ToArray (
  211. typeof (XmlSchemaParticle));
  212. }
  213. public void GetUnspecifiedDefaultAttributes (ArrayList list)
  214. {
  215. if (transition != Transition.StartTag)
  216. throw new InvalidOperationException ("Method 'GetUnsoecifiedDefaultAttributes' works only when the validator state is inside a start tag.");
  217. foreach (XmlSchemaAttribute attr
  218. in GetExpectedAttributes ())
  219. if (attr.ValidatedDefaultValue != null || attr.ValidatedFixedValue != null)
  220. list.Add (attr);
  221. list.AddRange (defaultAttributes);
  222. }
  223. // State Controller
  224. public void AddSchema (XmlSchema schema)
  225. {
  226. schemas.Add (schema);
  227. schemas.Compile ();
  228. }
  229. public void Initialize ()
  230. {
  231. Initialize (null);
  232. }
  233. public void Initialize (SOMObject startType)
  234. {
  235. this.startType = startType;
  236. transition = Transition.Content;
  237. state = new XsdParticleStateManager ();
  238. if (!schemas.IsCompiled)
  239. schemas.Compile ();
  240. }
  241. // It must be called at the end of the validation (to check
  242. // identity constraints etc.).
  243. public void EndValidation ()
  244. {
  245. CheckState (Transition.Content);
  246. transition = Transition.Finished;
  247. if (schemas.Count == 0)
  248. return;
  249. if (depth > 0)
  250. throw new InvalidOperationException (String.Format ("There are {0} open element(s). ValidateEndElement() must be called for each open element.", depth));
  251. // 3.3.4 ElementLocallyValidElement 7 = Root Valid.
  252. if (!IgnoreIdentity &&
  253. idManager.HasMissingIDReferences ())
  254. HandleError ("There are missing ID references: " + idManager.GetMissingIDString ());
  255. }
  256. // I guess it is for validation error recovery
  257. [MonoTODO ("Find out how XmlSchemaInfo is used.")]
  258. public void SkipToEndElement (XmlSchemaInfo info)
  259. {
  260. CheckState (Transition.Content);
  261. if (schemas.Count == 0)
  262. return;
  263. state.PopContext ();
  264. }
  265. public object ValidateAttribute (
  266. string localName,
  267. string ns,
  268. string attributeValue,
  269. XmlSchemaInfo info)
  270. {
  271. return ValidateAttribute (localName, ns,
  272. delegate () { return info.SchemaType.Datatype.ParseValue (attributeValue, nameTable, nsResolver); },
  273. info);
  274. }
  275. // I guess this weird XmlValueGetter is for such case that
  276. // value might not be required (and thus it improves
  277. // performance in some cases. Doh).
  278. // The return value is typed primitive, is possible.
  279. // AttDeriv
  280. public object ValidateAttribute (
  281. string localName,
  282. string ns,
  283. XmlValueGetter attributeValue,
  284. XmlSchemaInfo info)
  285. {
  286. CheckState (Transition.StartTag);
  287. QName qname = new QName (localName, ns);
  288. if (occuredAtts.Contains (qname))
  289. throw new InvalidOperationException (String.Format ("Attribute '{0}' has already been validated in the same element.", qname));
  290. occuredAtts.Add (qname);
  291. if (ns == XmlNamespaceManager.XmlnsXmlns)
  292. return null;
  293. if (schemas.Count == 0)
  294. return null;
  295. // 3.3.4 Element Locally Valid (Type) - attribute
  296. if (Context.ActualType is ComplexType)
  297. return AssessAttributeElementLocallyValidType (localName, ns, attributeValue, info);
  298. else
  299. HandleError ("Current simple type cannot accept attributes other than schema instance namespace.");
  300. return null;
  301. }
  302. // StartTagOpenDeriv
  303. public void ValidateElement (
  304. string localName,
  305. string ns,
  306. XmlSchemaInfo info)
  307. {
  308. ValidateElement (localName, ns, info, null, null, null, null);
  309. }
  310. public void ValidateElement (
  311. string localName,
  312. string ns,
  313. XmlSchemaInfo info,
  314. string xsiType,
  315. string xsiNil,
  316. string schemaLocation,
  317. string noNsSchemaLocation)
  318. {
  319. CheckState (Transition.Content);
  320. transition = Transition.StartTag;
  321. if (schemaLocation != null)
  322. HandleSchemaLocation (schemaLocation);
  323. if (noNsSchemaLocation != null)
  324. HandleNoNSSchemaLocation (noNsSchemaLocation);
  325. elementQNameStack.Add (new XmlQualifiedName (localName, ns));
  326. if (schemas.Count == 0)
  327. return;
  328. #region ID Constraints
  329. if (!IgnoreIdentity)
  330. idManager.OnStartElement ();
  331. #endregion
  332. defaultAttributes = emptyAttributeArray;
  333. // If there is no schema information, then no validation is performed.
  334. if (skipValidationDepth < 0 || depth <= skipValidationDepth) {
  335. if (shouldValidateCharacters)
  336. ValidateEndSimpleContent (null);
  337. AssessOpenStartElementSchemaValidity (localName, ns);
  338. }
  339. if (xsiNil != null)
  340. HandleXsiNil (xsiNil, info);
  341. if (xsiType != null)
  342. HandleXsiType (xsiType);
  343. shouldValidateCharacters = true;
  344. if (info != null) {
  345. info.IsNil = xsiNilDepth >= 0;
  346. info.SchemaElement = Context.Element;
  347. info.SchemaType = Context.ActualSchemaType;
  348. info.SchemaAttribute = null;
  349. info.IsDefault = false;
  350. info.MemberType = null;
  351. // FIXME: supply Validity (really useful?)
  352. }
  353. }
  354. public object ValidateEndElement (XmlSchemaInfo info)
  355. {
  356. return ValidateEndElement (info, null);
  357. }
  358. // The return value is typed primitive, if supplied.
  359. // Parameter 'var' seems to be converted into the type
  360. // represented by current simple content type. (try passing
  361. // some kind of object to this method to check the behavior.)
  362. // EndTagDeriv
  363. [MonoTODO ("Handle 'var' parameter.")]
  364. public object ValidateEndElement (XmlSchemaInfo info,
  365. object var)
  366. {
  367. // If it is going to validate an empty element, then
  368. // first validate end of attributes.
  369. if (transition == Transition.StartTag)
  370. ValidateEndOfAttributes (info);
  371. CheckState (Transition.Content);
  372. elementQNameStack.RemoveAt (elementQNameStack.Count - 1);
  373. if (schemas.Count == 0)
  374. return null;
  375. if (depth == 0)
  376. throw new InvalidOperationException ("There was no corresponding call to 'ValidateElement' method.");
  377. depth--;
  378. object ret = null;
  379. if (depth == skipValidationDepth)
  380. skipValidationDepth = -1;
  381. else if (skipValidationDepth < 0 || depth <= skipValidationDepth)
  382. ret = AssessEndElementSchemaValidity (info);
  383. return ret;
  384. }
  385. // StartTagCloseDeriv
  386. // FIXME: fill validity inside this invocation.
  387. public void ValidateEndOfAttributes (XmlSchemaInfo info)
  388. {
  389. try {
  390. CheckState (Transition.StartTag);
  391. transition = Transition.Content;
  392. if (schemas.Count == 0)
  393. return;
  394. AssessCloseStartElementSchemaValidity (info);
  395. } finally {
  396. occuredAtts.Clear ();
  397. }
  398. }
  399. // LAMESPEC: It should also receive XmlSchemaInfo so that
  400. // a validator application can receive simple type or
  401. // or content type validation errors.
  402. public void ValidateText (string value)
  403. {
  404. ValidateText (delegate () { return value; });
  405. }
  406. // TextDeriv ... without text. Maybe typed check is done by
  407. // ValidateAtomicValue().
  408. public void ValidateText (XmlValueGetter getter)
  409. {
  410. CheckState (Transition.Content);
  411. if (schemas.Count == 0)
  412. return;
  413. ComplexType ct = Context.ActualType as ComplexType;
  414. if (ct != null && storedCharacters.Length > 0) {
  415. switch (ct.ContentType) {
  416. case XmlSchemaContentType.ElementOnly:
  417. case XmlSchemaContentType.Empty:
  418. HandleError ("Not allowed character content was found.");
  419. break;
  420. }
  421. }
  422. ValidateCharacters (getter);
  423. }
  424. public void ValidateWhitespace (string value)
  425. {
  426. ValidateWhitespace (delegate () { return value; });
  427. }
  428. // TextDeriv...?
  429. [MonoTODO]
  430. public void ValidateWhitespace (XmlValueGetter getter)
  431. {
  432. CheckState (Transition.Content);
  433. if (schemas.Count == 0)
  434. return;
  435. // throw new NotImplementedException ();
  436. }
  437. #endregion
  438. #region Error handling
  439. private void HandleError (string message)
  440. {
  441. HandleError (message, null, false);
  442. }
  443. private void HandleError (
  444. string message, Exception innerException)
  445. {
  446. HandleError (message, innerException, false);
  447. }
  448. private void HandleError (string message,
  449. Exception innerException, bool isWarning)
  450. {
  451. if (isWarning && IgnoreWarnings)
  452. return;
  453. ValException vex = new ValException (
  454. message, nominalEventSender, BaseUri,
  455. null, innerException);
  456. HandleError (vex, isWarning);
  457. }
  458. private void HandleError (ValException exception)
  459. {
  460. HandleError (exception, false);
  461. }
  462. private void HandleError (ValException exception, bool isWarning)
  463. {
  464. if (isWarning && IgnoreWarnings)
  465. return;
  466. if (ValidationEventHandler == null)
  467. throw exception;
  468. ValidationEventArgs e = new ValidationEventArgs (
  469. exception,
  470. exception.Message,
  471. isWarning ? XmlSeverityType.Warning :
  472. XmlSeverityType.Error);
  473. ValidationEventHandler (nominalEventSender, e);
  474. }
  475. #endregion
  476. private void CheckState (Transition expected)
  477. {
  478. if (transition != expected) {
  479. if (transition == Transition.None)
  480. throw new InvalidOperationException ("Initialize() must be called before processing validation.");
  481. else
  482. throw new InvalidOperationException (
  483. String.Format ("Unexpected attempt to validation state transition from {0} to {1} was happened.",
  484. transition,
  485. expected));
  486. }
  487. }
  488. private XsElement FindElement (string name, string ns)
  489. {
  490. return (XsElement) schemas.GlobalElements [new XmlQualifiedName (name, ns)];
  491. }
  492. private XmlSchemaType FindType (XmlQualifiedName qname)
  493. {
  494. return (XmlSchemaType) schemas.GlobalTypes [qname];
  495. }
  496. #region Type Validation
  497. private void ValidateStartElementParticle (
  498. string localName, string ns)
  499. {
  500. if (Context.State == null)
  501. return;
  502. Context.XsiType = null;
  503. state.CurrentElement = null;
  504. Context.EvaluateStartElement (localName,
  505. ns);
  506. if (Context.IsInvalid)
  507. HandleError ("Invalid start element: " + ns + ":" + localName);
  508. Context.SetElement (state.CurrentElement);
  509. }
  510. private void AssessOpenStartElementSchemaValidity (
  511. string localName, string ns)
  512. {
  513. // If the reader is inside xsi:nil (and failed
  514. // on validation), then simply skip its content.
  515. if (xsiNilDepth >= 0 && xsiNilDepth < depth)
  516. HandleError ("Element item appeared, while current element context is nil.");
  517. ValidateStartElementParticle (localName, ns);
  518. // Create Validation Root, if not exist.
  519. // [Schema Validity Assessment (Element) 1.1]
  520. if (Context.Element == null) {
  521. state.CurrentElement = FindElement (localName, ns);
  522. Context.SetElement (state.CurrentElement);
  523. }
  524. #region Key Constraints
  525. if (!IgnoreIdentity)
  526. ValidateKeySelectors ();
  527. ValidateKeyFields (false, xsiNilDepth == depth,
  528. Context.ActualType, null, null, null);
  529. #endregion
  530. }
  531. private void AssessCloseStartElementSchemaValidity (XmlSchemaInfo info)
  532. {
  533. if (Context.XsiType != null)
  534. AssessCloseStartElementLocallyValidType (info);
  535. else if (Context.Element != null) {
  536. // element locally valid is checked only when
  537. // xsi:type does not exist.
  538. AssessElementLocallyValidElement ();
  539. if (Context.Element.ElementType != null)
  540. AssessCloseStartElementLocallyValidType (info);
  541. }
  542. if (Context.Element == null) {
  543. switch (state.ProcessContents) {
  544. case ContentProc.Skip:
  545. break;
  546. case ContentProc.Lax:
  547. break;
  548. default:
  549. QName current = (QName) elementQNameStack [elementQNameStack.Count - 1];
  550. if (Context.XsiType == null &&
  551. (schemas.Contains (current.Namespace) ||
  552. !schemas.MissedSubComponents (current.Namespace)))
  553. HandleError ("Element declaration for " + current + " is missing.");
  554. break;
  555. }
  556. }
  557. // Proceed to the next depth.
  558. state.PushContext ();
  559. XsdValidationState next = null;
  560. if (state.ProcessContents == ContentProc.Skip)
  561. skipValidationDepth = depth;
  562. else {
  563. // create child particle state.
  564. ComplexType xsComplexType = Context.ActualType as ComplexType;
  565. if (xsComplexType != null)
  566. next = state.Create (xsComplexType.ValidatableParticle);
  567. else if (state.ProcessContents == ContentProc.Lax)
  568. next = state.Create (XmlSchemaAny.AnyTypeContent);
  569. else
  570. next = state.Create (XmlSchemaParticle.Empty);
  571. }
  572. Context.State = next;
  573. depth++;
  574. }
  575. // It must be invoked after xsi:nil turned out not to be in
  576. // this element.
  577. private void AssessElementLocallyValidElement ()
  578. {
  579. XsElement element = Context.Element;
  580. XmlQualifiedName qname = (XmlQualifiedName) elementQNameStack [elementQNameStack.Count - 1];
  581. // 1.
  582. if (element == null)
  583. HandleError ("Element declaration is required for " + qname);
  584. // 2.
  585. if (element.ActualIsAbstract)
  586. HandleError ("Abstract element declaration was specified for " + qname);
  587. // 3. is checked inside ValidateAttribute().
  588. }
  589. // 3.3.4 Element Locally Valid (Type)
  590. private void AssessCloseStartElementLocallyValidType (XmlSchemaInfo info)
  591. {
  592. object schemaType = Context.ActualType;
  593. if (schemaType == null) { // 1.
  594. HandleError ("Schema type does not exist.");
  595. return;
  596. }
  597. ComplexType cType = schemaType as ComplexType;
  598. SimpleType sType = schemaType as SimpleType;
  599. if (sType != null) {
  600. // 3.1.1.
  601. // Attributes are checked in ValidateAttribute().
  602. } else if (cType != null) {
  603. // 3.2. Also, 2. is checked there.
  604. AssessCloseStartElementLocallyValidComplexType (cType, info);
  605. }
  606. }
  607. // 3.4.4 Element Locally Valid (Complex Type)
  608. // FIXME: use SchemaInfo for somewhere (? it is passed to ValidateEndOfAttributes() for some reason)
  609. private void AssessCloseStartElementLocallyValidComplexType (ComplexType cType, XmlSchemaInfo info)
  610. {
  611. // 1.
  612. if (cType.IsAbstract) {
  613. HandleError ("Target complex type is abstract.");
  614. return;
  615. }
  616. // 2 (xsi:nil and content prohibition)
  617. // See AssessStartElementSchemaValidity() and ValidateCharacters()
  618. // 3. attribute uses and 5. wild IDs are handled at
  619. // ValidateAttribute().
  620. // Collect default attributes.
  621. // 4.
  622. foreach (XsAttribute attr in GetExpectedAttributes ()) {
  623. if (attr.ValidatedUse == XmlSchemaUse.Required &&
  624. attr.ValidatedFixedValue == null)
  625. HandleError ("Required attribute " + attr.QualifiedName + " was not found.");
  626. else if (attr.ValidatedDefaultValue != null || attr.ValidatedFixedValue != null)
  627. defaultAttributesCache.Add (attr);
  628. }
  629. if (defaultAttributesCache.Count == 0)
  630. defaultAttributes = emptyAttributeArray;
  631. else
  632. defaultAttributes = (XsAttribute [])
  633. defaultAttributesCache.ToArray (
  634. typeof (XsAttribute));
  635. defaultAttributesCache.Clear ();
  636. // 5. wild IDs was already checked at ValidateAttribute().
  637. }
  638. private object AssessAttributeElementLocallyValidType (string localName, string ns, XmlValueGetter getter, XmlSchemaInfo info)
  639. {
  640. ComplexType cType = Context.ActualType as ComplexType;
  641. XmlQualifiedName qname = new XmlQualifiedName (localName, ns);
  642. // including 3.10.4 Item Valid (Wildcard)
  643. XmlSchemaObject attMatch = XmlSchemaUtil.FindAttributeDeclaration (ns, schemas, cType, qname);
  644. if (attMatch == null)
  645. HandleError ("Attribute declaration was not found for " + qname);
  646. XsAttribute attdecl = attMatch as XsAttribute;
  647. if (attdecl != null) {
  648. AssessAttributeLocallyValidUse (attdecl);
  649. return AssessAttributeLocallyValid (attdecl, info, getter);
  650. } // otherwise anyAttribute or null.
  651. return null;
  652. }
  653. // 3.2.4 Attribute Locally Valid and 3.4.4
  654. private object AssessAttributeLocallyValid (XsAttribute attr, XmlSchemaInfo info, XmlValueGetter getter)
  655. {
  656. // 2. - 4.
  657. if (attr.AttributeType == null)
  658. HandleError ("Attribute type is missing for " + attr.QualifiedName);
  659. XsDatatype dt = attr.AttributeType as XsDatatype;
  660. if (dt == null)
  661. dt = ((SimpleType) attr.AttributeType).Datatype;
  662. // It is a bit heavy process, so let's omit as long as possible ;-)
  663. if (dt != SimpleType.AnySimpleType || attr.ValidatedFixedValue != null) {
  664. object parsedValue = null;
  665. try {
  666. parsedValue = getter ();
  667. } catch (Exception ex) { // It is inevitable and bad manner.
  668. HandleError ("Attribute value is invalid against its data type " + dt.TokenizedType, ex);
  669. }
  670. XmlSchemaType type = info != null ? info.SchemaType : null;
  671. if (attr.ValidatedFixedValue != null &&
  672. !XmlSchemaUtil.IsSchemaDatatypeEquals (
  673. attr.AttributeSchemaType.Datatype as XsdAnySimpleType, attr.ValidatedFixedTypedValue, type != null ? type.Datatype as XsdAnySimpleType : null, parsedValue)) {
  674. HandleError ("The value of the attribute " + attr.QualifiedName + " does not match with its fixed value.");
  675. parsedValue = attr.ValidatedFixedTypedValue;
  676. }
  677. #region ID Constraints
  678. if (!IgnoreIdentity) {
  679. string error = idManager.AssessEachAttributeIdentityConstraint (dt, parsedValue, ((QName) elementQNameStack [elementQNameStack.Count - 1]).Name);
  680. if (error != null)
  681. HandleError (error);
  682. }
  683. #endregion
  684. #region Key Constraints
  685. if (!IgnoreIdentity)
  686. ValidateKeyFields (
  687. true,
  688. false,
  689. attr.AttributeType,
  690. attr.QualifiedName.Name,
  691. attr.QualifiedName.Namespace,
  692. getter);
  693. #endregion
  694. return parsedValue;
  695. }
  696. return null;
  697. }
  698. private void AssessAttributeLocallyValidUse (XsAttribute attr)
  699. {
  700. // This is extra check than spec 3.5.4
  701. if (attr.ValidatedUse == XmlSchemaUse.Prohibited)
  702. HandleError ("Attribute " + attr.QualifiedName + " is prohibited in this context.");
  703. }
  704. private object AssessEndElementSchemaValidity (
  705. XmlSchemaInfo info)
  706. {
  707. ValidateEndElementParticle (); // validate against childrens' state.
  708. object ret = ValidateEndSimpleContent (info);
  709. // 3.3.4 Assess ElementLocallyValidElement 5: value constraints.
  710. // 3.3.4 Assess ElementLocallyValidType 3.1.3. = StringValid(3.14.4)
  711. // => ValidateEndSimpleContent ().
  712. #region Key Constraints
  713. if (!IgnoreIdentity)
  714. ValidateEndElementKeyConstraints ();
  715. #endregion
  716. // Reset xsi:nil, if required.
  717. if (xsiNilDepth == depth)
  718. xsiNilDepth = -1;
  719. return ret;
  720. }
  721. private void ValidateEndElementParticle ()
  722. {
  723. if (Context.State != null) {
  724. if (!Context.EvaluateEndElement ()) {
  725. HandleError ("Invalid end element. There are still required content items.");
  726. }
  727. }
  728. state.PopContext ();
  729. }
  730. // Utility for missing validation completion related to child items.
  731. private void ValidateCharacters (XmlValueGetter getter)
  732. {
  733. if (xsiNilDepth >= 0 && xsiNilDepth < depth)
  734. HandleError ("Element item appeared, while current element context is nil.");
  735. if (shouldValidateCharacters)
  736. storedCharacters.Append (getter ());
  737. }
  738. // Utility for missing validation completion related to child items.
  739. private object ValidateEndSimpleContent (XmlSchemaInfo info)
  740. {
  741. object ret = null;
  742. if (shouldValidateCharacters)
  743. ret = ValidateEndSimpleContentCore (info);
  744. shouldValidateCharacters = false;
  745. storedCharacters.Length = 0;
  746. return ret;
  747. }
  748. private object ValidateEndSimpleContentCore (XmlSchemaInfo info)
  749. {
  750. if (Context.ActualType == null)
  751. return null;
  752. string value = storedCharacters.ToString ();
  753. object ret = null;
  754. if (value.Length == 0) {
  755. // 3.3.4 Element Locally Valid (Element) 5.1.2
  756. if (Context.Element != null) {
  757. if (Context.Element.ValidatedDefaultValue != null)
  758. value = Context.Element.ValidatedDefaultValue;
  759. }
  760. }
  761. XsDatatype dt = Context.ActualType as XsDatatype;
  762. SimpleType st = Context.ActualType as SimpleType;
  763. if (dt == null) {
  764. if (st != null) {
  765. dt = st.Datatype;
  766. } else {
  767. ComplexType ct = Context.ActualType as ComplexType;
  768. dt = ct.Datatype;
  769. switch (ct.ContentType) {
  770. case XmlSchemaContentType.ElementOnly:
  771. case XmlSchemaContentType.Empty:
  772. if (value.Length > 0)
  773. HandleError ("Character content not allowed.");
  774. break;
  775. }
  776. }
  777. }
  778. if (dt != null) {
  779. // 3.3.4 Element Locally Valid (Element) :: 5.2.2.2. Fixed value constraints
  780. if (Context.Element != null && Context.Element.ValidatedFixedValue != null)
  781. if (value != Context.Element.ValidatedFixedValue)
  782. HandleError ("Fixed value constraint was not satisfied.");
  783. ret = AssessStringValid (st, dt, value);
  784. }
  785. #region Key Constraints
  786. if (!IgnoreIdentity)
  787. ValidateSimpleContentIdentity (dt, value);
  788. #endregion
  789. shouldValidateCharacters = false;
  790. if (info != null) {
  791. info.IsNil = xsiNilDepth >= 0;
  792. info.SchemaElement = null;
  793. info.SchemaType = Context.ActualType as XmlSchemaType;
  794. if (info.SchemaType == null)
  795. info.SchemaType = XmlSchemaType.GetBuiltInSimpleType (dt.TypeCode);
  796. info.SchemaAttribute = null;
  797. info.IsDefault = false; // FIXME: might be true
  798. info.MemberType = null; // FIXME: check
  799. // FIXME: supply Validity (really useful?)
  800. }
  801. return ret;
  802. }
  803. // 3.14.4 String Valid
  804. private object AssessStringValid (SimpleType st,
  805. XsDatatype dt, string value)
  806. {
  807. XsDatatype validatedDatatype = dt;
  808. object ret = null;
  809. if (st != null) {
  810. string normalized = validatedDatatype.Normalize (value);
  811. string [] values;
  812. XsDatatype itemDatatype;
  813. SimpleType itemSimpleType;
  814. switch (st.DerivedBy) {
  815. case XmlSchemaDerivationMethod.List:
  816. SimpleTypeList listContent = st.Content as SimpleTypeList;
  817. values = normalized.Split (XmlChar.WhitespaceChars);
  818. // LAMESPEC: Types of each element in
  819. // the returned list might be
  820. // inconsistent, so basically returning
  821. // value does not make sense without
  822. // explicit runtime type information
  823. // for base primitive type.
  824. object [] retValues = new object [values.Length];
  825. itemDatatype = listContent.ValidatedListItemType as XsDatatype;
  826. itemSimpleType = listContent.ValidatedListItemType as SimpleType;
  827. for (int vi = 0; vi < values.Length; vi++) {
  828. string each = values [vi];
  829. if (each == String.Empty)
  830. continue;
  831. // validate against ValidatedItemType
  832. if (itemDatatype != null) {
  833. try {
  834. retValues [vi] = itemDatatype.ParseValue (each, nameTable, nsResolver);
  835. } catch (Exception ex) { // It is inevitable and bad manner.
  836. HandleError ("List type value contains one or more invalid values.", ex);
  837. break;
  838. }
  839. }
  840. else
  841. AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
  842. }
  843. ret = retValues;
  844. break;
  845. case XmlSchemaDerivationMethod.Union:
  846. SimpleTypeUnion union = st.Content as SimpleTypeUnion;
  847. {
  848. string each = normalized;
  849. // validate against ValidatedItemType
  850. bool passed = false;
  851. foreach (object eachType in union.ValidatedTypes) {
  852. itemDatatype = eachType as XsDatatype;
  853. itemSimpleType = eachType as SimpleType;
  854. if (itemDatatype != null) {
  855. try {
  856. ret = itemDatatype.ParseValue (each, nameTable, nsResolver);
  857. } catch (Exception) { // It is inevitable and bad manner.
  858. continue;
  859. }
  860. }
  861. else {
  862. try {
  863. ret = AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
  864. } catch (ValException) {
  865. continue;
  866. }
  867. }
  868. passed = true;
  869. break;
  870. }
  871. if (!passed) {
  872. HandleError ("Union type value contains one or more invalid values.");
  873. break;
  874. }
  875. }
  876. break;
  877. case XmlSchemaDerivationMethod.Restriction:
  878. SimpleTypeRest str = st.Content as SimpleTypeRest;
  879. // facet validation
  880. if (str != null) {
  881. /* Don't forget to validate against inherited type's facets
  882. * Could we simplify this by assuming that the basetype will also
  883. * be restriction?
  884. * */
  885. // mmm, will check later.
  886. SimpleType baseType = st.BaseXmlSchemaType as SimpleType;
  887. if (baseType != null) {
  888. ret = AssessStringValid (baseType, dt, value);
  889. }
  890. if (!str.ValidateValueWithFacets (value, nameTable)) {
  891. HandleError ("Specified value was invalid against the facets.");
  892. break;
  893. }
  894. }
  895. validatedDatatype = st.Datatype;
  896. break;
  897. }
  898. }
  899. if (validatedDatatype != null) {
  900. try {
  901. ret = validatedDatatype.ParseValue (value, nameTable, nsResolver);
  902. } catch (Exception ex) { // It is inevitable and bad manner.
  903. HandleError (String.Format ("Invalidly typed data was specified."), ex);
  904. }
  905. }
  906. return ret;
  907. }
  908. #endregion
  909. #region Key Constraints Validation
  910. private XsdKeyTable CreateNewKeyTable (XmlSchemaIdentityConstraint ident)
  911. {
  912. XsdKeyTable seq = new XsdKeyTable (ident);
  913. seq.StartDepth = depth;
  914. this.keyTables.Add (seq);
  915. return seq;
  916. }
  917. // 3.11.4 Identity Constraint Satisfied
  918. private void ValidateKeySelectors ()
  919. {
  920. if (tmpKeyrefPool != null)
  921. tmpKeyrefPool.Clear ();
  922. if (Context.Element != null && Context.Element.Constraints.Count > 0) {
  923. // (a) Create new key sequences, if required.
  924. for (int i = 0; i < Context.Element.Constraints.Count; i++) {
  925. XmlSchemaIdentityConstraint ident = (XmlSchemaIdentityConstraint) Context.Element.Constraints [i];
  926. XsdKeyTable seq = CreateNewKeyTable (ident);
  927. if (ident is XmlSchemaKeyref) {
  928. if (tmpKeyrefPool == null)
  929. tmpKeyrefPool = new ArrayList ();
  930. tmpKeyrefPool.Add (seq);
  931. }
  932. }
  933. }
  934. // (b) Evaluate current key sequences.
  935. for (int i = 0; i < keyTables.Count; i++) {
  936. XsdKeyTable seq = (XsdKeyTable) keyTables [i];
  937. if (seq.SelectorMatches (this.elementQNameStack, depth) != null) {
  938. // creates and registers new entry.
  939. XsdKeyEntry entry = new XsdKeyEntry (seq, depth, lineInfo);
  940. seq.Entries.Add (entry);
  941. }
  942. }
  943. }
  944. private void ValidateKeyFields (bool isAttr, bool isNil, object schemaType, string attrName, string attrNs, XmlValueGetter getter)
  945. {
  946. // (c) Evaluate field paths.
  947. for (int i = 0; i < keyTables.Count; i++) {
  948. XsdKeyTable seq = (XsdKeyTable) keyTables [i];
  949. // If possible, create new field entry candidates.
  950. for (int j = 0; j < seq.Entries.Count; j++) {
  951. try {
  952. seq.Entries [j].ProcessMatch (
  953. isAttr,
  954. elementQNameStack,
  955. nominalEventSender,
  956. nameTable,
  957. BaseUri,
  958. schemaType,
  959. nsResolver,
  960. lineInfo,
  961. depth,
  962. attrName,
  963. attrNs,
  964. getter == null ?
  965. null :
  966. getter (),
  967. isNil,
  968. currentKeyFieldConsumers);
  969. } catch (ValException ex) {
  970. HandleError (ex);
  971. }
  972. }
  973. }
  974. }
  975. private void ProcessKeyEntryOne (XsdKeyEntry entry, bool isAttr, bool isNil, object schemaType, string attrName, string attrNs, XmlValueGetter getter)
  976. {
  977. }
  978. private void ValidateEndElementKeyConstraints ()
  979. {
  980. // Reset Identity constraints.
  981. for (int i = 0; i < keyTables.Count; i++) {
  982. XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
  983. if (seq.StartDepth == depth) {
  984. ValidateEndKeyConstraint (seq);
  985. } else {
  986. for (int k = 0; k < seq.Entries.Count; k++) {
  987. XsdKeyEntry entry = seq.Entries [k] as XsdKeyEntry;
  988. // Remove finished (maybe key not found) entries.
  989. if (entry.StartDepth == depth) {
  990. if (entry.KeyFound)
  991. seq.FinishedEntries.Add (entry);
  992. else if (seq.SourceSchemaIdentity is XmlSchemaKey)
  993. HandleError ("Key sequence is missing.");
  994. seq.Entries.RemoveAt (k);
  995. k--;
  996. }
  997. // Pop validated key depth to find two or more fields.
  998. else {
  999. for (int j = 0; j < entry.KeyFields.Count; j++) {
  1000. XsdKeyEntryField kf = entry.KeyFields [j];
  1001. if (!kf.FieldFound && kf.FieldFoundDepth == depth) {
  1002. kf.FieldFoundDepth = 0;
  1003. kf.FieldFoundPath = null;
  1004. }
  1005. }
  1006. }
  1007. }
  1008. }
  1009. }
  1010. for (int i = 0; i < keyTables.Count; i++) {
  1011. XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
  1012. if (seq.StartDepth == depth) {
  1013. keyTables.RemoveAt (i);
  1014. i--;
  1015. }
  1016. }
  1017. }
  1018. private void ValidateEndKeyConstraint (XsdKeyTable seq)
  1019. {
  1020. ArrayList errors = new ArrayList ();
  1021. for (int i = 0; i < seq.Entries.Count; i++) {
  1022. XsdKeyEntry entry = (XsdKeyEntry) seq.Entries [i];
  1023. if (entry.KeyFound)
  1024. continue;
  1025. if (seq.SourceSchemaIdentity is XmlSchemaKey)
  1026. errors.Add ("line " + entry.SelectorLineNumber + "position " + entry.SelectorLinePosition);
  1027. }
  1028. if (errors.Count > 0)
  1029. HandleError ("Invalid identity constraints were found. Key was not found. "
  1030. + String.Join (", ", errors.ToArray (typeof (string)) as string []));
  1031. errors.Clear ();
  1032. // Find reference target
  1033. XmlSchemaKeyref xsdKeyref = seq.SourceSchemaIdentity as XmlSchemaKeyref;
  1034. if (xsdKeyref != null) {
  1035. for (int i = this.keyTables.Count - 1; i >= 0; i--) {
  1036. XsdKeyTable target = this.keyTables [i] as XsdKeyTable;
  1037. if (target.SourceSchemaIdentity == xsdKeyref.Target) {
  1038. seq.ReferencedKey = target;
  1039. for (int j = 0; j < seq.FinishedEntries.Count; j++) {
  1040. XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [j];
  1041. for (int k = 0; k < target.FinishedEntries.Count; k++) {
  1042. XsdKeyEntry targetEntry = (XsdKeyEntry) target.FinishedEntries [k];
  1043. if (entry.CompareIdentity (targetEntry)) {
  1044. entry.KeyRefFound = true;
  1045. break;
  1046. }
  1047. }
  1048. }
  1049. }
  1050. }
  1051. if (seq.ReferencedKey == null)
  1052. HandleError ("Target key was not found.");
  1053. for (int i = 0; i < seq.FinishedEntries.Count; i++) {
  1054. XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [i];
  1055. if (!entry.KeyRefFound)
  1056. errors.Add (" line " + entry.SelectorLineNumber + ", position " + entry.SelectorLinePosition);
  1057. }
  1058. if (errors.Count > 0)
  1059. HandleError ("Invalid identity constraints were found. Referenced key was not found: "
  1060. + String.Join (" / ", errors.ToArray (typeof (string)) as string []));
  1061. }
  1062. }
  1063. private void ValidateSimpleContentIdentity (
  1064. XmlSchemaDatatype dt, string value)
  1065. {
  1066. // Identity field value
  1067. if (currentKeyFieldConsumers != null) {
  1068. while (this.currentKeyFieldConsumers.Count > 0) {
  1069. XsdKeyEntryField field = this.currentKeyFieldConsumers [0] as XsdKeyEntryField;
  1070. if (field.Identity != null)
  1071. HandleError ("Two or more identical field was found. Former value is '" + field.Identity + "' .");
  1072. object identity = null; // This means empty value
  1073. if (dt != null) {
  1074. try {
  1075. identity = dt.ParseValue (value, nameTable, nsResolver);
  1076. } catch (Exception ex) { // It is inevitable and bad manner.
  1077. HandleError ("Identity value is invalid against its data type " + dt.TokenizedType, ex);
  1078. }
  1079. }
  1080. if (identity == null)
  1081. identity = value;
  1082. if (!field.SetIdentityField (identity, depth == xsiNilDepth, dt as XsdAnySimpleType, depth, lineInfo))
  1083. HandleError ("Two or more identical key value was found: '" + value + "' .");
  1084. this.currentKeyFieldConsumers.RemoveAt (0);
  1085. }
  1086. }
  1087. }
  1088. #endregion
  1089. #region xsi:type
  1090. private object GetXsiType (string name)
  1091. {
  1092. object xsiType = null;
  1093. XmlQualifiedName typeQName =
  1094. XmlQualifiedName.Parse (name, nsResolver);
  1095. if (typeQName == ComplexType.AnyTypeName)
  1096. xsiType = ComplexType.AnyType;
  1097. else if (XmlSchemaUtil.IsBuiltInDatatypeName (typeQName))
  1098. xsiType = XsDatatype.FromName (typeQName);
  1099. else
  1100. xsiType = FindType (typeQName);
  1101. return xsiType;
  1102. }
  1103. private void HandleXsiType (string typename)
  1104. {
  1105. XsElement element = Context.Element;
  1106. object xsiType = GetXsiType (typename);
  1107. if (xsiType == null) {
  1108. HandleError ("The instance type was not found: " + typename);
  1109. return;
  1110. }
  1111. XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
  1112. if (xsiSchemaType != null && Context.Element != null) {
  1113. XmlSchemaType elemBaseType = element.ElementType as XmlSchemaType;
  1114. if (elemBaseType != null && (xsiSchemaType.DerivedBy & elemBaseType.FinalResolved) != 0)
  1115. HandleError ("The instance type is prohibited by the type of the context element.");
  1116. if (elemBaseType != xsiType && (xsiSchemaType.DerivedBy & element.BlockResolved) != 0)
  1117. HandleError ("The instance type is prohibited by the context element.");
  1118. }
  1119. ComplexType xsiComplexType = xsiType as ComplexType;
  1120. if (xsiComplexType != null && xsiComplexType.IsAbstract)
  1121. HandleError ("The instance type is abstract: " + typename);
  1122. else {
  1123. // If current schema type exists, then this xsi:type must be
  1124. // valid extension of that type. See 1.2.1.2.4.
  1125. if (element != null) {
  1126. AssessLocalTypeDerivationOK (xsiType, element.ElementType, element.BlockResolved);
  1127. }
  1128. // See also ValidateEndOfAttributes().
  1129. Context.XsiType = xsiType;
  1130. }
  1131. }
  1132. // It is common to ElementLocallyValid::4 and SchemaValidityAssessment::1.2.1.2.4
  1133. private void AssessLocalTypeDerivationOK (object xsiType, object baseType, XmlSchemaDerivationMethod flag)
  1134. {
  1135. XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
  1136. ComplexType baseComplexType = baseType as ComplexType;
  1137. ComplexType xsiComplexType = xsiSchemaType as ComplexType;
  1138. if (xsiType != baseType) {
  1139. // Extracted (not extraneous) check for 3.4.6 TypeDerivationOK.
  1140. if (baseComplexType != null)
  1141. flag |= baseComplexType.BlockResolved;
  1142. if (flag == XmlSchemaDerivationMethod.All) {
  1143. HandleError ("Prohibited element type substitution.");
  1144. return;
  1145. } else if (xsiSchemaType != null && (flag & xsiSchemaType.DerivedBy) != 0) {
  1146. HandleError ("Prohibited element type substitution.");
  1147. return;
  1148. }
  1149. }
  1150. if (xsiComplexType != null)
  1151. try {
  1152. xsiComplexType.ValidateTypeDerivationOK (baseType, null, null);
  1153. } catch (ValException ex) {
  1154. HandleError (ex);
  1155. }
  1156. else {
  1157. SimpleType xsiSimpleType = xsiType as SimpleType;
  1158. if (xsiSimpleType != null) {
  1159. try {
  1160. xsiSimpleType.ValidateTypeDerivationOK (baseType, null, null, true);
  1161. } catch (ValException ex) {
  1162. HandleError (ex);
  1163. }
  1164. }
  1165. else if (xsiType is XsDatatype) {
  1166. // do nothing
  1167. }
  1168. else
  1169. HandleError ("Primitive data type cannot be derived type using xsi:type specification.");
  1170. }
  1171. }
  1172. #endregion
  1173. private void HandleXsiNil (string value, XmlSchemaInfo info)
  1174. {
  1175. XsElement element = Context.Element;
  1176. if (!element.ActualIsNillable) {
  1177. HandleError (String.Format ("Current element '{0}' is not nillable and thus does not allow occurence of 'nil' attribute.", Context.Element.QualifiedName));
  1178. return;
  1179. }
  1180. value = value.Trim (XmlChar.WhitespaceChars);
  1181. // 3.2.
  1182. // Note that 3.2.1 xsi:nil constraints are to be
  1183. // validated in AssessElementSchemaValidity() and
  1184. // ValidateCharacters().
  1185. if (value == "true") {
  1186. if (element.ValidatedFixedValue != null)
  1187. HandleError ("Schema instance nil was specified, where the element declaration for " + element.QualifiedName + "has fixed value constraints.");
  1188. xsiNilDepth = depth;
  1189. if (info != null)
  1190. info.IsNil = true;
  1191. }
  1192. }
  1193. #region External schema resolution
  1194. private XmlSchema ReadExternalSchema (string uri)
  1195. {
  1196. Uri absUri = new Uri (SourceUri, uri.Trim (XmlChar.WhitespaceChars));
  1197. XmlTextReader xtr = null;
  1198. try {
  1199. xtr = new XmlTextReader (absUri.ToString (),
  1200. (Stream) xmlResolver.GetEntity (
  1201. absUri, null, typeof (Stream)),
  1202. nameTable);
  1203. return XmlSchema.Read (
  1204. xtr, ValidationEventHandler);
  1205. } finally {
  1206. if (xtr != null)
  1207. xtr.Close ();
  1208. }
  1209. }
  1210. private void HandleSchemaLocation (string schemaLocation)
  1211. {
  1212. if (xmlResolver == null)
  1213. return;
  1214. XmlSchema schema = null;
  1215. bool schemaAdded = false;
  1216. string [] tmp = null;
  1217. try {
  1218. schemaLocation = XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.Token).Datatype.ParseValue (schemaLocation, null, null) as string;
  1219. tmp = schemaLocation.Split (XmlChar.WhitespaceChars);
  1220. } catch (Exception ex) {
  1221. HandleError ("Invalid schemaLocation attribute format.", ex, true);
  1222. tmp = new string [0];
  1223. }
  1224. if (tmp.Length % 2 != 0)
  1225. HandleError ("Invalid schemaLocation attribute format.");
  1226. for (int i = 0; i < tmp.Length; i += 2) {
  1227. try {
  1228. schema = ReadExternalSchema (tmp [i + 1]);
  1229. } catch (Exception ex) { // It is inevitable and bad manner.
  1230. HandleError ("Could not resolve schema location URI: " + schemaLocation, ex, true);
  1231. continue;
  1232. }
  1233. if (schema.TargetNamespace == null)
  1234. schema.TargetNamespace = tmp [i];
  1235. else if (schema.TargetNamespace != tmp [i])
  1236. HandleError ("Specified schema has different target namespace.");
  1237. if (schema != null) {
  1238. if (!schemas.Contains (schema.TargetNamespace)) {
  1239. schemaAdded = true;
  1240. schemas.Add (schema);
  1241. }
  1242. }
  1243. }
  1244. if (schemaAdded)
  1245. schemas.Compile ();
  1246. }
  1247. private void HandleNoNSSchemaLocation (string noNsSchemaLocation)
  1248. {
  1249. if (xmlResolver == null)
  1250. return;
  1251. XmlSchema schema = null;
  1252. bool schemaAdded = false;
  1253. try {
  1254. schema = ReadExternalSchema (noNsSchemaLocation);
  1255. } catch (Exception ex) { // It is inevitable and bad manner.
  1256. HandleError ("Could not resolve schema location URI: " + noNsSchemaLocation, ex, true);
  1257. }
  1258. if (schema != null && schema.TargetNamespace != null)
  1259. HandleError ("Specified schema has different target namespace.");
  1260. if (schema != null) {
  1261. if (!schemas.Contains (schema.TargetNamespace)) {
  1262. schemaAdded = true;
  1263. schemas.Add (schema);
  1264. }
  1265. }
  1266. if (schemaAdded)
  1267. schemas.Compile ();
  1268. }
  1269. #endregion
  1270. }
  1271. }
  1272. #endif