XmlSchemaValidator.cs 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446
  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. [MonoTODO]
  154. public Uri 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 string BaseUri {
  163. get { return sourceUri != null ? sourceUri.AbsoluteUri : String.Empty; }
  164. }
  165. private XsdValidationContext Context {
  166. get { return state.Context; }
  167. }
  168. private bool IgnoreWarnings {
  169. get { return (options & ValidationFlags
  170. .ReportValidationWarnings) == 0; }
  171. }
  172. private bool IgnoreIdentity {
  173. get { return (options & ValidationFlags
  174. .ProcessIdentityConstraints) == 0; }
  175. }
  176. #endregion
  177. #region Public methods
  178. // State Monitor
  179. public XmlSchemaAttribute [] GetExpectedAttributes ()
  180. {
  181. ComplexType cType = Context.ActualType as ComplexType;
  182. if (cType == null)
  183. return emptyAttributeArray;
  184. ArrayList al = new ArrayList ();
  185. foreach (DictionaryEntry entry in cType.AttributeUses)
  186. if (!occuredAtts.Contains ((QName) entry.Key))
  187. al.Add (entry.Value);
  188. return (XsAttribute [])
  189. al.ToArray (typeof (XsAttribute));
  190. }
  191. private void CollectAtomicParticles (XmlSchemaParticle p,
  192. ArrayList al)
  193. {
  194. if (p is XmlSchemaGroupBase) {
  195. foreach (XmlSchemaParticle c in
  196. ((XmlSchemaGroupBase) p).Items)
  197. CollectAtomicParticles (c, al);
  198. }
  199. else
  200. al.Add (p);
  201. }
  202. [MonoTODO ("Need some tests.")]
  203. // Its behavior is not obvious. For example, it does not
  204. // contain groups (xs:sequence/xs:choice/xs:all). Since it
  205. // might contain xs:any, it could not be of type element[].
  206. public XmlSchemaParticle [] GetExpectedParticles ()
  207. {
  208. ArrayList al = new ArrayList ();
  209. Context.State.GetExpectedParticles (al);
  210. ArrayList ret = new ArrayList ();
  211. foreach (XmlSchemaParticle p in al)
  212. CollectAtomicParticles (p, ret);
  213. return (XmlSchemaParticle []) ret.ToArray (
  214. typeof (XmlSchemaParticle));
  215. }
  216. public void GetUnspecifiedDefaultAttributes (ArrayList list)
  217. {
  218. if (transition != Transition.StartTag)
  219. throw new InvalidOperationException ("Method 'GetUnsoecifiedDefaultAttributes' works only when the validator state is inside a start tag.");
  220. foreach (XmlSchemaAttribute attr
  221. in GetExpectedAttributes ())
  222. if (attr.ValidatedDefaultValue != null || attr.ValidatedFixedValue != null)
  223. list.Add (attr);
  224. list.AddRange (defaultAttributes);
  225. }
  226. // State Controller
  227. public void AddSchema (XmlSchema schema)
  228. {
  229. schemas.Add (schema);
  230. schemas.Compile ();
  231. }
  232. public void Initialize ()
  233. {
  234. Initialize (null);
  235. }
  236. public void Initialize (SOMObject startType)
  237. {
  238. this.startType = startType;
  239. transition = Transition.Content;
  240. state = new XsdParticleStateManager ();
  241. if (!schemas.IsCompiled)
  242. schemas.Compile ();
  243. }
  244. // It must be called at the end of the validation (to check
  245. // identity constraints etc.).
  246. public void EndValidation ()
  247. {
  248. CheckState (Transition.Content);
  249. transition = Transition.Finished;
  250. if (schemas.Count == 0)
  251. return;
  252. if (depth > 0)
  253. throw new InvalidOperationException (String.Format ("There are {0} open element(s). ValidateEndElement() must be called for each open element.", depth));
  254. // 3.3.4 ElementLocallyValidElement 7 = Root Valid.
  255. if (!IgnoreIdentity &&
  256. idManager.HasMissingIDReferences ())
  257. HandleError ("There are missing ID references: " + idManager.GetMissingIDString ());
  258. }
  259. // I guess it is for validation error recovery
  260. [MonoTODO ("Find out how XmlSchemaInfo is used.")]
  261. public void SkipToEndElement (XmlSchemaInfo info)
  262. {
  263. CheckState (Transition.Content);
  264. if (schemas.Count == 0)
  265. return;
  266. state.PopContext ();
  267. }
  268. public object ValidateAttribute (
  269. string localName,
  270. string ns,
  271. string attributeValue,
  272. XmlSchemaInfo info)
  273. {
  274. return ValidateAttribute (localName, ns,
  275. delegate () { return info.SchemaType.Datatype.ParseValue (attributeValue, nameTable, nsResolver); },
  276. info);
  277. }
  278. // I guess this weird XmlValueGetter is for such case that
  279. // value might not be required (and thus it improves
  280. // performance in some cases. Doh).
  281. // The return value is typed primitive, is possible.
  282. // AttDeriv
  283. public object ValidateAttribute (
  284. string localName,
  285. string ns,
  286. XmlValueGetter attributeValue,
  287. XmlSchemaInfo info)
  288. {
  289. CheckState (Transition.StartTag);
  290. QName qname = new QName (localName, ns);
  291. if (occuredAtts.Contains (qname))
  292. throw new InvalidOperationException (String.Format ("Attribute '{0}' has already been validated in the same element.", qname));
  293. occuredAtts.Add (qname);
  294. if (ns == XmlNamespaceManager.XmlnsXmlns)
  295. return null;
  296. if (schemas.Count == 0)
  297. return null;
  298. // 3.3.4 Element Locally Valid (Type) - attribute
  299. if (Context.ActualType is ComplexType)
  300. return AssessAttributeElementLocallyValidType (localName, ns, attributeValue, info);
  301. else
  302. HandleError ("Current simple type cannot accept attributes other than schema instance namespace.");
  303. return null;
  304. }
  305. // StartTagOpenDeriv
  306. public void ValidateElement (
  307. string localName,
  308. string ns,
  309. XmlSchemaInfo info)
  310. {
  311. ValidateElement (localName, ns, info, null, null, null, null);
  312. }
  313. public void ValidateElement (
  314. string localName,
  315. string ns,
  316. XmlSchemaInfo info,
  317. string xsiType,
  318. string xsiNil,
  319. string schemaLocation,
  320. string noNsSchemaLocation)
  321. {
  322. CheckState (Transition.Content);
  323. transition = Transition.StartTag;
  324. if (schemaLocation != null)
  325. HandleSchemaLocation (schemaLocation);
  326. if (noNsSchemaLocation != null)
  327. HandleNoNSSchemaLocation (noNsSchemaLocation);
  328. elementQNameStack.Add (new XmlQualifiedName (localName, ns));
  329. if (schemas.Count == 0)
  330. return;
  331. #region ID Constraints
  332. if (!IgnoreIdentity)
  333. idManager.OnStartElement ();
  334. #endregion
  335. defaultAttributes = emptyAttributeArray;
  336. // If there is no schema information, then no validation is performed.
  337. if (skipValidationDepth < 0 || depth <= skipValidationDepth) {
  338. if (shouldValidateCharacters)
  339. ValidateEndSimpleContent (null);
  340. AssessOpenStartElementSchemaValidity (localName, ns);
  341. }
  342. if (xsiNil != null)
  343. HandleXsiNil (xsiNil, info);
  344. if (xsiType != null)
  345. HandleXsiType (xsiType);
  346. shouldValidateCharacters = true;
  347. if (info != null) {
  348. info.IsNil = xsiNilDepth >= 0;
  349. info.SchemaElement = Context.Element;
  350. info.SchemaType = Context.ActualSchemaType;
  351. info.SchemaAttribute = null;
  352. info.IsDefault = false;
  353. info.MemberType = null;
  354. // FIXME: supply Validity (really useful?)
  355. }
  356. }
  357. public object ValidateEndElement (XmlSchemaInfo info)
  358. {
  359. return ValidateEndElement (info, null);
  360. }
  361. // The return value is typed primitive, if supplied.
  362. // Parameter 'var' seems to be converted into the type
  363. // represented by current simple content type. (try passing
  364. // some kind of object to this method to check the behavior.)
  365. // EndTagDeriv
  366. [MonoTODO ("Handle 'var' parameter.")]
  367. public object ValidateEndElement (XmlSchemaInfo info,
  368. object var)
  369. {
  370. // If it is going to validate an empty element, then
  371. // first validate end of attributes.
  372. if (transition == Transition.StartTag)
  373. ValidateEndOfAttributes (info);
  374. CheckState (Transition.Content);
  375. elementQNameStack.RemoveAt (elementQNameStack.Count - 1);
  376. if (schemas.Count == 0)
  377. return null;
  378. if (depth == 0)
  379. throw new InvalidOperationException ("There was no corresponding call to 'ValidateElement' method.");
  380. depth--;
  381. object ret = null;
  382. if (depth == skipValidationDepth)
  383. skipValidationDepth = -1;
  384. else if (skipValidationDepth < 0 || depth <= skipValidationDepth)
  385. ret = AssessEndElementSchemaValidity (info);
  386. return ret;
  387. }
  388. // StartTagCloseDeriv
  389. // FIXME: fill validity inside this invocation.
  390. public void ValidateEndOfAttributes (XmlSchemaInfo info)
  391. {
  392. try {
  393. CheckState (Transition.StartTag);
  394. transition = Transition.Content;
  395. if (schemas.Count == 0)
  396. return;
  397. AssessCloseStartElementSchemaValidity (info);
  398. } finally {
  399. occuredAtts.Clear ();
  400. }
  401. }
  402. // LAMESPEC: It should also receive XmlSchemaInfo so that
  403. // a validator application can receive simple type or
  404. // or content type validation errors.
  405. public void ValidateText (string value)
  406. {
  407. ValidateText (delegate () { return value; });
  408. }
  409. // TextDeriv ... without text. Maybe typed check is done by
  410. // ValidateAtomicValue().
  411. public void ValidateText (XmlValueGetter getter)
  412. {
  413. CheckState (Transition.Content);
  414. if (schemas.Count == 0)
  415. return;
  416. ComplexType ct = Context.ActualType as ComplexType;
  417. if (ct != null && storedCharacters.Length > 0) {
  418. switch (ct.ContentType) {
  419. case XmlSchemaContentType.ElementOnly:
  420. case XmlSchemaContentType.Empty:
  421. HandleError ("Not allowed character content was found.");
  422. break;
  423. }
  424. }
  425. ValidateCharacters (getter);
  426. }
  427. public void ValidateWhitespace (string value)
  428. {
  429. ValidateWhitespace (delegate () { return value; });
  430. }
  431. // TextDeriv...?
  432. [MonoTODO]
  433. public void ValidateWhitespace (XmlValueGetter getter)
  434. {
  435. CheckState (Transition.Content);
  436. if (schemas.Count == 0)
  437. return;
  438. // throw new NotImplementedException ();
  439. }
  440. #endregion
  441. #region Error handling
  442. private void HandleError (string message)
  443. {
  444. HandleError (message, null, false);
  445. }
  446. private void HandleError (
  447. string message, Exception innerException)
  448. {
  449. HandleError (message, innerException, false);
  450. }
  451. private void HandleError (string message,
  452. Exception innerException, bool isWarning)
  453. {
  454. if (isWarning && IgnoreWarnings)
  455. return;
  456. ValException vex = new ValException (
  457. message, nominalEventSender, BaseUri,
  458. null, innerException);
  459. HandleError (vex, isWarning);
  460. }
  461. private void HandleError (ValException exception)
  462. {
  463. HandleError (exception, false);
  464. }
  465. private void HandleError (ValException exception, bool isWarning)
  466. {
  467. if (isWarning && IgnoreWarnings)
  468. return;
  469. if (ValidationEventHandler == null)
  470. throw exception;
  471. ValidationEventArgs e = new ValidationEventArgs (
  472. exception,
  473. exception.Message,
  474. isWarning ? XmlSeverityType.Warning :
  475. XmlSeverityType.Error);
  476. ValidationEventHandler (nominalEventSender, e);
  477. }
  478. #endregion
  479. private void CheckState (Transition expected)
  480. {
  481. if (transition != expected) {
  482. if (transition == Transition.None)
  483. throw new InvalidOperationException ("Initialize() must be called before processing validation.");
  484. else
  485. throw new InvalidOperationException (
  486. String.Format ("Unexpected attempt to validation state transition from {0} to {1} was happened.",
  487. transition,
  488. expected));
  489. }
  490. }
  491. private XsElement FindElement (string name, string ns)
  492. {
  493. return (XsElement) schemas.GlobalElements [new XmlQualifiedName (name, ns)];
  494. }
  495. private XmlSchemaType FindType (XmlQualifiedName qname)
  496. {
  497. return (XmlSchemaType) schemas.GlobalTypes [qname];
  498. }
  499. #region Type Validation
  500. private void ValidateStartElementParticle (
  501. string localName, string ns)
  502. {
  503. if (Context.State == null)
  504. return;
  505. Context.XsiType = null;
  506. state.CurrentElement = null;
  507. Context.EvaluateStartElement (localName,
  508. ns);
  509. if (Context.IsInvalid)
  510. HandleError ("Invalid start element: " + ns + ":" + localName);
  511. Context.SetElement (state.CurrentElement);
  512. }
  513. private void AssessOpenStartElementSchemaValidity (
  514. string localName, string ns)
  515. {
  516. // If the reader is inside xsi:nil (and failed
  517. // on validation), then simply skip its content.
  518. if (xsiNilDepth >= 0 && xsiNilDepth < depth)
  519. HandleError ("Element item appeared, while current element context is nil.");
  520. ValidateStartElementParticle (localName, ns);
  521. // Create Validation Root, if not exist.
  522. // [Schema Validity Assessment (Element) 1.1]
  523. if (Context.Element == null) {
  524. state.CurrentElement = FindElement (localName, ns);
  525. Context.SetElement (state.CurrentElement);
  526. }
  527. #region Key Constraints
  528. if (!IgnoreIdentity)
  529. ValidateKeySelectors ();
  530. ValidateKeyFields (false, xsiNilDepth == depth,
  531. Context.ActualType, null, null, null);
  532. #endregion
  533. }
  534. private void AssessCloseStartElementSchemaValidity (XmlSchemaInfo info)
  535. {
  536. if (Context.XsiType != null)
  537. AssessCloseStartElementLocallyValidType (info);
  538. else if (Context.Element != null) {
  539. // element locally valid is checked only when
  540. // xsi:type does not exist.
  541. AssessElementLocallyValidElement ();
  542. if (Context.Element.ElementType != null)
  543. AssessCloseStartElementLocallyValidType (info);
  544. }
  545. if (Context.Element == null) {
  546. switch (state.ProcessContents) {
  547. case ContentProc.Skip:
  548. break;
  549. case ContentProc.Lax:
  550. break;
  551. default:
  552. QName current = (QName) elementQNameStack [elementQNameStack.Count - 1];
  553. if (Context.XsiType == null &&
  554. (schemas.Contains (current.Namespace) ||
  555. !schemas.MissedSubComponents (current.Namespace)))
  556. HandleError ("Element declaration for " + current + " is missing.");
  557. break;
  558. }
  559. }
  560. // Proceed to the next depth.
  561. state.PushContext ();
  562. XsdValidationState next = null;
  563. if (state.ProcessContents == ContentProc.Skip)
  564. skipValidationDepth = depth;
  565. else {
  566. // create child particle state.
  567. ComplexType xsComplexType = Context.ActualType as ComplexType;
  568. if (xsComplexType != null)
  569. next = state.Create (xsComplexType.ValidatableParticle);
  570. else if (state.ProcessContents == ContentProc.Lax)
  571. next = state.Create (XmlSchemaAny.AnyTypeContent);
  572. else
  573. next = state.Create (XmlSchemaParticle.Empty);
  574. }
  575. Context.State = next;
  576. depth++;
  577. }
  578. // It must be invoked after xsi:nil turned out not to be in
  579. // this element.
  580. private void AssessElementLocallyValidElement ()
  581. {
  582. XsElement element = Context.Element;
  583. XmlQualifiedName qname = (XmlQualifiedName) elementQNameStack [elementQNameStack.Count - 1];
  584. // 1.
  585. if (element == null)
  586. HandleError ("Element declaration is required for " + qname);
  587. // 2.
  588. if (element.ActualIsAbstract)
  589. HandleError ("Abstract element declaration was specified for " + qname);
  590. // 3. is checked inside ValidateAttribute().
  591. }
  592. // 3.3.4 Element Locally Valid (Type)
  593. private void AssessCloseStartElementLocallyValidType (XmlSchemaInfo info)
  594. {
  595. object schemaType = Context.ActualType;
  596. if (schemaType == null) { // 1.
  597. HandleError ("Schema type does not exist.");
  598. return;
  599. }
  600. ComplexType cType = schemaType as ComplexType;
  601. SimpleType sType = schemaType as SimpleType;
  602. if (sType != null) {
  603. // 3.1.1.
  604. // Attributes are checked in ValidateAttribute().
  605. } else if (cType != null) {
  606. // 3.2. Also, 2. is checked there.
  607. AssessCloseStartElementLocallyValidComplexType (cType, info);
  608. }
  609. }
  610. // 3.4.4 Element Locally Valid (Complex Type)
  611. // FIXME: use SchemaInfo for somewhere (? it is passed to ValidateEndOfAttributes() for some reason)
  612. private void AssessCloseStartElementLocallyValidComplexType (ComplexType cType, XmlSchemaInfo info)
  613. {
  614. // 1.
  615. if (cType.IsAbstract) {
  616. HandleError ("Target complex type is abstract.");
  617. return;
  618. }
  619. // 2 (xsi:nil and content prohibition)
  620. // See AssessStartElementSchemaValidity() and ValidateCharacters()
  621. // 3. attribute uses and 5. wild IDs are handled at
  622. // ValidateAttribute().
  623. // Collect default attributes.
  624. // 4.
  625. foreach (XsAttribute attr in GetExpectedAttributes ()) {
  626. if (attr.ValidatedUse == XmlSchemaUse.Required &&
  627. attr.ValidatedFixedValue == null)
  628. HandleError ("Required attribute " + attr.QualifiedName + " was not found.");
  629. else if (attr.ValidatedDefaultValue != null || attr.ValidatedFixedValue != null)
  630. defaultAttributesCache.Add (attr);
  631. }
  632. if (defaultAttributesCache.Count == 0)
  633. defaultAttributes = emptyAttributeArray;
  634. else
  635. defaultAttributes = (XsAttribute [])
  636. defaultAttributesCache.ToArray (
  637. typeof (XsAttribute));
  638. defaultAttributesCache.Clear ();
  639. // 5. wild IDs was already checked at ValidateAttribute().
  640. }
  641. private object AssessAttributeElementLocallyValidType (string localName, string ns, XmlValueGetter getter, XmlSchemaInfo info)
  642. {
  643. ComplexType cType = Context.ActualType as ComplexType;
  644. XmlQualifiedName qname = new XmlQualifiedName (localName, ns);
  645. // including 3.10.4 Item Valid (Wildcard)
  646. XmlSchemaObject attMatch = XmlSchemaUtil.FindAttributeDeclaration (ns, schemas, cType, qname);
  647. if (attMatch == null)
  648. HandleError ("Attribute declaration was not found for " + qname);
  649. XsAttribute attdecl = attMatch as XsAttribute;
  650. if (attdecl != null) {
  651. AssessAttributeLocallyValidUse (attdecl);
  652. return AssessAttributeLocallyValid (attdecl, info, getter);
  653. } // otherwise anyAttribute or null.
  654. return null;
  655. }
  656. // 3.2.4 Attribute Locally Valid and 3.4.4
  657. private object AssessAttributeLocallyValid (XsAttribute attr, XmlSchemaInfo info, XmlValueGetter getter)
  658. {
  659. // 2. - 4.
  660. if (attr.AttributeType == null)
  661. HandleError ("Attribute type is missing for " + attr.QualifiedName);
  662. XsDatatype dt = attr.AttributeType as XsDatatype;
  663. if (dt == null)
  664. dt = ((SimpleType) attr.AttributeType).Datatype;
  665. // It is a bit heavy process, so let's omit as long as possible ;-)
  666. if (dt != SimpleType.AnySimpleType || attr.ValidatedFixedValue != null) {
  667. object parsedValue = null;
  668. try {
  669. parsedValue = getter ();
  670. } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
  671. HandleError ("Attribute value is invalid against its data type " + dt.TokenizedType, ex);
  672. }
  673. XmlSchemaType type = info != null ? info.SchemaType : null;
  674. if (attr.ValidatedFixedValue != null &&
  675. !XmlSchemaUtil.IsSchemaDatatypeEquals (
  676. attr.AttributeSchemaType.Datatype as XsdAnySimpleType, attr.ValidatedFixedTypedValue, type != null ? type.Datatype as XsdAnySimpleType : null, parsedValue)) {
  677. HandleError ("The value of the attribute " + attr.QualifiedName + " does not match with its fixed value.");
  678. parsedValue = attr.ValidatedFixedTypedValue;
  679. }
  680. #region ID Constraints
  681. if (!IgnoreIdentity) {
  682. string error = idManager.AssessEachAttributeIdentityConstraint (dt, parsedValue, ((QName) elementQNameStack [elementQNameStack.Count - 1]).Name);
  683. if (error != null)
  684. HandleError (error);
  685. }
  686. #endregion
  687. #region Key Constraints
  688. if (!IgnoreIdentity)
  689. ValidateKeyFields (
  690. true,
  691. false,
  692. attr.AttributeType,
  693. attr.QualifiedName.Name,
  694. attr.QualifiedName.Namespace,
  695. getter);
  696. #endregion
  697. return parsedValue;
  698. }
  699. return null;
  700. }
  701. private void AssessAttributeLocallyValidUse (XsAttribute attr)
  702. {
  703. // This is extra check than spec 3.5.4
  704. if (attr.ValidatedUse == XmlSchemaUse.Prohibited)
  705. HandleError ("Attribute " + attr.QualifiedName + " is prohibited in this context.");
  706. }
  707. private object AssessEndElementSchemaValidity (
  708. XmlSchemaInfo info)
  709. {
  710. ValidateEndElementParticle (); // validate against childrens' state.
  711. object ret = ValidateEndSimpleContent (info);
  712. // 3.3.4 Assess ElementLocallyValidElement 5: value constraints.
  713. // 3.3.4 Assess ElementLocallyValidType 3.1.3. = StringValid(3.14.4)
  714. // => ValidateEndSimpleContent ().
  715. #region Key Constraints
  716. if (!IgnoreIdentity)
  717. ValidateEndElementKeyConstraints ();
  718. #endregion
  719. // Reset xsi:nil, if required.
  720. if (xsiNilDepth == depth)
  721. xsiNilDepth = -1;
  722. return ret;
  723. }
  724. private void ValidateEndElementParticle ()
  725. {
  726. if (Context.State != null) {
  727. if (!Context.EvaluateEndElement ()) {
  728. HandleError ("Invalid end element. There are still required content items.");
  729. }
  730. }
  731. state.PopContext ();
  732. }
  733. // Utility for missing validation completion related to child items.
  734. private void ValidateCharacters (XmlValueGetter getter)
  735. {
  736. if (xsiNilDepth >= 0 && xsiNilDepth < depth)
  737. HandleError ("Element item appeared, while current element context is nil.");
  738. if (shouldValidateCharacters)
  739. storedCharacters.Append (getter ());
  740. }
  741. // Utility for missing validation completion related to child items.
  742. private object ValidateEndSimpleContent (XmlSchemaInfo info)
  743. {
  744. object ret = null;
  745. if (shouldValidateCharacters)
  746. ret = ValidateEndSimpleContentCore (info);
  747. shouldValidateCharacters = false;
  748. storedCharacters.Length = 0;
  749. return ret;
  750. }
  751. private object ValidateEndSimpleContentCore (XmlSchemaInfo info)
  752. {
  753. if (Context.ActualType == null)
  754. return null;
  755. string value = storedCharacters.ToString ();
  756. object ret = null;
  757. if (value.Length == 0) {
  758. // 3.3.4 Element Locally Valid (Element) 5.1.2
  759. if (Context.Element != null) {
  760. if (Context.Element.ValidatedDefaultValue != null)
  761. value = Context.Element.ValidatedDefaultValue;
  762. }
  763. }
  764. XsDatatype dt = Context.ActualType as XsDatatype;
  765. SimpleType st = Context.ActualType as SimpleType;
  766. if (dt == null) {
  767. if (st != null) {
  768. dt = st.Datatype;
  769. } else {
  770. ComplexType ct = Context.ActualType as ComplexType;
  771. dt = ct.Datatype;
  772. switch (ct.ContentType) {
  773. case XmlSchemaContentType.ElementOnly:
  774. case XmlSchemaContentType.Empty:
  775. if (value.Length > 0)
  776. HandleError ("Character content not allowed.");
  777. break;
  778. }
  779. }
  780. }
  781. if (dt != null) {
  782. // 3.3.4 Element Locally Valid (Element) :: 5.2.2.2. Fixed value constraints
  783. if (Context.Element != null && Context.Element.ValidatedFixedValue != null)
  784. if (value != Context.Element.ValidatedFixedValue)
  785. HandleError ("Fixed value constraint was not satisfied.");
  786. ret = AssessStringValid (st, dt, value);
  787. }
  788. #region Key Constraints
  789. if (!IgnoreIdentity)
  790. ValidateSimpleContentIdentity (dt, value);
  791. #endregion
  792. shouldValidateCharacters = false;
  793. if (info != null) {
  794. info.IsNil = xsiNilDepth >= 0;
  795. info.SchemaElement = null;
  796. info.SchemaType = st;
  797. if (st == null)
  798. info.SchemaType = XmlSchemaType.GetBuiltInSimpleType (dt.TypeCode);
  799. info.SchemaAttribute = null;
  800. info.IsDefault = false; // FIXME: might be true
  801. info.MemberType = null; // FIXME: check
  802. // FIXME: supply Validity (really useful?)
  803. }
  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. BaseUri,
  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 (string value, 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. value = value.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. #region External schema resolution
  1197. private XmlSchema ReadExternalSchema (string uri)
  1198. {
  1199. Uri absUri = new Uri (SourceUri, uri.Trim (XmlChar.WhitespaceChars));
  1200. XmlTextReader xtr = null;
  1201. try {
  1202. xtr = new XmlTextReader (absUri.ToString (),
  1203. (Stream) xmlResolver.GetEntity (
  1204. absUri, null, typeof (Stream)),
  1205. nameTable);
  1206. return XmlSchema.Read (
  1207. xtr, ValidationEventHandler);
  1208. } finally {
  1209. if (xtr != null)
  1210. xtr.Close ();
  1211. }
  1212. }
  1213. private void HandleSchemaLocation (string schemaLocation)
  1214. {
  1215. if (xmlResolver == null)
  1216. return;
  1217. XmlSchema schema = null;
  1218. bool schemaAdded = false;
  1219. string [] tmp = null;
  1220. try {
  1221. schemaLocation = XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.Token).Datatype.ParseValue (schemaLocation, null, null) as string;
  1222. tmp = schemaLocation.Split (XmlChar.WhitespaceChars);
  1223. } catch (Exception ex) {
  1224. HandleError ("Invalid schemaLocation attribute format.", ex, true);
  1225. tmp = new string [0];
  1226. }
  1227. if (tmp.Length % 2 != 0)
  1228. HandleError ("Invalid schemaLocation attribute format.");
  1229. for (int i = 0; i < tmp.Length; i += 2) {
  1230. try {
  1231. schema = ReadExternalSchema (tmp [i + 1]);
  1232. } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
  1233. HandleError ("Could not resolve schema location URI: " + schemaLocation, ex, true);
  1234. continue;
  1235. }
  1236. if (schema.TargetNamespace == null)
  1237. schema.TargetNamespace = tmp [i];
  1238. else if (schema.TargetNamespace != tmp [i])
  1239. HandleError ("Specified schema has different target namespace.");
  1240. if (schema != null) {
  1241. if (!schemas.Contains (schema.TargetNamespace)) {
  1242. schemaAdded = true;
  1243. schemas.Add (schema);
  1244. }
  1245. }
  1246. }
  1247. if (schemaAdded)
  1248. schemas.Compile ();
  1249. }
  1250. private void HandleNoNSSchemaLocation (string noNsSchemaLocation)
  1251. {
  1252. if (xmlResolver == null)
  1253. return;
  1254. XmlSchema schema = null;
  1255. bool schemaAdded = false;
  1256. try {
  1257. schema = ReadExternalSchema (noNsSchemaLocation);
  1258. } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
  1259. HandleError ("Could not resolve schema location URI: " + noNsSchemaLocation, ex, true);
  1260. }
  1261. if (schema != null && schema.TargetNamespace != null)
  1262. HandleError ("Specified schema has different target namespace.");
  1263. if (schema != null) {
  1264. if (!schemas.Contains (schema.TargetNamespace)) {
  1265. schemaAdded = true;
  1266. schemas.Add (schema);
  1267. }
  1268. }
  1269. if (schemaAdded)
  1270. schemas.Compile ();
  1271. }
  1272. #endregion
  1273. }
  1274. }
  1275. #endif