XmlSchemaValidator.cs 43 KB

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