PageRenderTime 59ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/mcs/class/System.XML/System.Xml.Schema/XmlSchemaValidator.cs

https://bitbucket.org/danipen/mono
C# | 1684 lines | 1314 code | 198 blank | 172 comment | 422 complexity | 1a3c2e8ea9e5940afa8dc512b7daafe5 MD5 | raw file
Possible License(s): Unlicense, Apache-2.0, LGPL-2.0, MPL-2.0-no-copyleft-exception, CC-BY-SA-3.0, GPL-2.0

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file