XmlSchemaValidator.cs 43 KB

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