XmlSchema.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  1. //
  2. // System.Xml.Schema.XmlSchema.cs
  3. //
  4. // Author:
  5. // Dwivedi, Ajay kumar [email protected]
  6. // Atsushi Enomoto [email protected]
  7. //
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System;
  29. using System.Collections;
  30. using System.Xml;
  31. using System.IO;
  32. using System.Xml.Serialization;
  33. using System.ComponentModel;
  34. namespace System.Xml.Schema
  35. {
  36. /// <summary>
  37. /// Summary description for XmlSchema.
  38. /// </summary>
  39. [XmlRoot ("schema",Namespace=XmlSchema.Namespace)]
  40. public class XmlSchema : XmlSchemaObject
  41. {
  42. //public constants
  43. public const string Namespace = "http://www.w3.org/2001/XMLSchema";
  44. public const string InstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance";
  45. internal const string XdtNamespace = "http://www.w3.org/2003/11/xpath-datatypes";
  46. //private fields
  47. private XmlSchemaForm attributeFormDefault ;
  48. private XmlSchemaObjectTable attributeGroups ;
  49. private XmlSchemaObjectTable attributes ;
  50. private XmlSchemaDerivationMethod blockDefault ;
  51. private XmlSchemaForm elementFormDefault ;
  52. private XmlSchemaObjectTable elements ;
  53. private XmlSchemaDerivationMethod finalDefault ;
  54. private XmlSchemaObjectTable groups ;
  55. private string id ;
  56. private XmlSchemaObjectCollection includes ;
  57. private XmlSchemaObjectCollection items ;
  58. private XmlSchemaObjectTable notations ;
  59. private XmlSchemaObjectTable schemaTypes ;
  60. private string targetNamespace ;
  61. private XmlAttribute[] unhandledAttributes ;
  62. private string version;
  63. // other post schema compilation infoset
  64. private Hashtable idCollection;
  65. private XmlSchemaObjectTable namedIdentities;
  66. private XmlSchemaSet schemas;
  67. private XmlNameTable nameTable;
  68. internal bool missedSubComponents;
  69. // Only compilation-time use
  70. private XmlSchemaObjectCollection compilationItems;
  71. private Hashtable handledUris;
  72. // Compiler specific things
  73. const string xmlname = "schema";
  74. public XmlSchema ()
  75. {
  76. attributeFormDefault= XmlSchemaForm.None;
  77. blockDefault = XmlSchemaDerivationMethod.None;
  78. elementFormDefault = XmlSchemaForm.None;
  79. finalDefault = XmlSchemaDerivationMethod.None;
  80. includes = new XmlSchemaObjectCollection();
  81. isCompiled = false;
  82. items = new XmlSchemaObjectCollection();
  83. attributeGroups = new XmlSchemaObjectTable();
  84. attributes = new XmlSchemaObjectTable();
  85. elements = new XmlSchemaObjectTable();
  86. groups = new XmlSchemaObjectTable();
  87. notations = new XmlSchemaObjectTable();
  88. schemaTypes = new XmlSchemaObjectTable();
  89. idCollection = new Hashtable ();
  90. namedIdentities = new XmlSchemaObjectTable();
  91. }
  92. #region Properties
  93. [DefaultValue (XmlSchemaForm.None)]
  94. [System.Xml.Serialization.XmlAttribute ("attributeFormDefault")]
  95. public XmlSchemaForm AttributeFormDefault
  96. {
  97. get{ return attributeFormDefault; }
  98. set{ this.attributeFormDefault = value;}
  99. }
  100. [DefaultValue (XmlSchemaDerivationMethod.None)]
  101. [System.Xml.Serialization.XmlAttribute ("blockDefault")]
  102. public XmlSchemaDerivationMethod BlockDefault
  103. {
  104. get{ return blockDefault;}
  105. set{ blockDefault = value;}
  106. }
  107. [DefaultValue (XmlSchemaDerivationMethod.None)]
  108. [System.Xml.Serialization.XmlAttribute ("finalDefault")]
  109. public XmlSchemaDerivationMethod FinalDefault
  110. {
  111. get{ return finalDefault; }
  112. set{ finalDefault = value; }
  113. }
  114. [DefaultValue (XmlSchemaForm.None)]
  115. [System.Xml.Serialization.XmlAttribute ("elementFormDefault")]
  116. public XmlSchemaForm ElementFormDefault
  117. {
  118. get{ return elementFormDefault; }
  119. set{ elementFormDefault = value; }
  120. }
  121. [System.Xml.Serialization.XmlAttribute ("targetNamespace")]
  122. public string TargetNamespace
  123. {
  124. get{ return targetNamespace; }
  125. set{ targetNamespace = value; }
  126. }
  127. [System.Xml.Serialization.XmlAttribute ("version")]
  128. public string Version
  129. {
  130. get{ return version; }
  131. set{ version = value; }
  132. }
  133. [XmlElement ("include",typeof(XmlSchemaInclude), Namespace="http://www.w3.org/2001/XMLSchema")]
  134. [XmlElement ("import",typeof(XmlSchemaImport), Namespace="http://www.w3.org/2001/XMLSchema")]
  135. [XmlElement ("redefine",typeof(XmlSchemaRedefine), Namespace="http://www.w3.org/2001/XMLSchema")]
  136. public XmlSchemaObjectCollection Includes
  137. {
  138. get{ return includes;}
  139. }
  140. [XmlElement ("simpleType", typeof (XmlSchemaSimpleType), Namespace="http://www.w3.org/2001/XMLSchema")]
  141. [XmlElement ("complexType", typeof (XmlSchemaComplexType), Namespace="http://www.w3.org/2001/XMLSchema")]
  142. [XmlElement ("group", typeof (XmlSchemaGroup),Namespace="http://www.w3.org/2001/XMLSchema")]
  143. //Only Schema's attributeGroup has type XmlSchemaAttributeGroup.
  144. //Others (complextype, restrictions etc) must have XmlSchemaAttributeGroupRef
  145. [XmlElement ("attributeGroup", typeof (XmlSchemaAttributeGroup), Namespace="http://www.w3.org/2001/XMLSchema")]
  146. [XmlElement ("element", typeof (XmlSchemaElement), Namespace="http://www.w3.org/2001/XMLSchema")]
  147. [XmlElement ("attribute", typeof (XmlSchemaAttribute), Namespace="http://www.w3.org/2001/XMLSchema")]
  148. [XmlElement ("notation", typeof (XmlSchemaNotation), Namespace="http://www.w3.org/2001/XMLSchema")]
  149. [XmlElement ("annotation", typeof (XmlSchemaAnnotation), Namespace="http://www.w3.org/2001/XMLSchema")]
  150. public XmlSchemaObjectCollection Items
  151. {
  152. get{ return items; }
  153. }
  154. [XmlIgnore]
  155. public bool IsCompiled
  156. {
  157. get{ return this.CompilationId != Guid.Empty; }
  158. }
  159. [XmlIgnore]
  160. public XmlSchemaObjectTable Attributes
  161. {
  162. get{ return attributes; }
  163. }
  164. [XmlIgnore]
  165. public XmlSchemaObjectTable AttributeGroups
  166. {
  167. get{ return attributeGroups; }
  168. }
  169. [XmlIgnore]
  170. public XmlSchemaObjectTable SchemaTypes
  171. {
  172. get{ return schemaTypes; }
  173. }
  174. [XmlIgnore]
  175. public XmlSchemaObjectTable Elements
  176. {
  177. get{ return elements; }
  178. }
  179. [System.Xml.Serialization.XmlAttribute ("id")]
  180. public string Id
  181. {
  182. get{ return id; }
  183. set{ id = value; }
  184. }
  185. [XmlAnyAttribute]
  186. public XmlAttribute [] UnhandledAttributes
  187. {
  188. get {
  189. if (unhandledAttributeList != null) {
  190. unhandledAttributes = (XmlAttribute []) unhandledAttributeList.ToArray (typeof (XmlAttribute));
  191. unhandledAttributeList = null;
  192. }
  193. return unhandledAttributes;
  194. }
  195. set {
  196. unhandledAttributes = value;
  197. unhandledAttributeList = null;
  198. }
  199. }
  200. [XmlIgnore]
  201. public XmlSchemaObjectTable Groups
  202. {
  203. get{ return groups; }
  204. }
  205. [XmlIgnore]
  206. public XmlSchemaObjectTable Notations
  207. {
  208. get{ return notations; }
  209. }
  210. internal Hashtable IDCollection
  211. {
  212. get { return idCollection; }
  213. }
  214. internal XmlSchemaObjectTable NamedIdentities
  215. {
  216. get { return namedIdentities; }
  217. }
  218. internal XmlSchemaSet Schemas
  219. {
  220. get { return schemas; }
  221. }
  222. #endregion
  223. #region Compile
  224. // Methods
  225. /// <summary>
  226. /// This compile method does two things:
  227. /// 1. It compiles and fills the PSVI dataset
  228. /// 2. Validates the schema by calling Validate method.
  229. /// Every XmlSchemaObject has a Compile Method which gets called.
  230. /// </summary>
  231. /// <remarks>
  232. /// 1. blockDefault must be one of #all | List of (extension | restriction | substitution)
  233. /// 2. finalDefault must be one of (#all | List of (extension | restriction| union| list))
  234. /// 3. id must be of type ID
  235. /// 4. targetNamespace should be any uri
  236. /// 5. version should be a normalizedString
  237. /// </remarks>
  238. public void Compile (ValidationEventHandler handler)
  239. {
  240. Compile (handler, new XmlUrlResolver ());
  241. }
  242. #if NET_1_1
  243. public void Compile (ValidationEventHandler handler, XmlResolver resolver)
  244. #else
  245. internal void Compile (ValidationEventHandler handler, XmlResolver resolver)
  246. #endif
  247. {
  248. Compile (handler, new Stack (), this, null, resolver);
  249. }
  250. internal void Compile (ValidationEventHandler handler, XmlSchemaSet col, XmlResolver resolver)
  251. {
  252. Compile (handler, new Stack (), this, col, resolver);
  253. }
  254. private void Compile (ValidationEventHandler handler, Stack schemaLocationStack, XmlSchema rootSchema, XmlSchemaSet col, XmlResolver resolver)
  255. {
  256. if (rootSchema != this) {
  257. CompilationId = rootSchema.CompilationId;
  258. schemas = rootSchema.schemas;
  259. }
  260. else {
  261. schemas = col;
  262. if (schemas == null) {
  263. schemas = new XmlSchemaSet ();
  264. schemas.CompilationId = Guid.NewGuid ();
  265. }
  266. CompilationId = schemas.CompilationId;
  267. this.idCollection.Clear ();
  268. }
  269. if (!schemas.Contains (this)) // e.g. xs:import
  270. schemas.Add (this);
  271. attributeGroups.Clear ();
  272. attributes.Clear ();
  273. elements.Clear ();
  274. groups.Clear ();
  275. notations.Clear ();
  276. schemaTypes.Clear ();
  277. namedIdentities.Clear ();
  278. //1. Union and List are not allowed in block default
  279. if (BlockDefault != XmlSchemaDerivationMethod.All) {
  280. if((BlockDefault & XmlSchemaDerivationMethod.List)!=0 )
  281. error(handler, "list is not allowed in blockDefault attribute");
  282. if((BlockDefault & XmlSchemaDerivationMethod.Union)!=0 )
  283. error(handler, "union is not allowed in blockDefault attribute");
  284. }
  285. //2. Substitution is not allowed in finaldefault.
  286. if (FinalDefault != XmlSchemaDerivationMethod.All) {
  287. if((FinalDefault & XmlSchemaDerivationMethod.Substitution)!=0 )
  288. error(handler, "substitution is not allowed in finalDefault attribute");
  289. }
  290. //3. id must be of type ID
  291. XmlSchemaUtil.CompileID(Id, this, this.IDCollection, handler);
  292. //4. targetNamespace should be of type anyURI or absent
  293. if (TargetNamespace != null) {
  294. if(!XmlSchemaUtil.CheckAnyUri (TargetNamespace))
  295. error(handler, TargetNamespace+" is not a valid value for targetNamespace attribute of schema");
  296. }
  297. //5. version should be of type normalizedString
  298. if (!XmlSchemaUtil.CheckNormalizedString(Version))
  299. error(handler, Version + "is not a valid value for version attribute of schema");
  300. // Compile the content of this schema
  301. compilationItems = new XmlSchemaObjectCollection ();
  302. for (int i = 0; i < Items.Count; i++) {
  303. #if NET_2_0
  304. Items [i].Parent = this;
  305. #endif
  306. compilationItems.Add (Items [i]);
  307. }
  308. if (this == rootSchema)
  309. handledUris = new Hashtable ();
  310. // First, we run into inclusion schemas to collect
  311. // compilation target items into compiledItems.
  312. for (int i = 0; i < Includes.Count; i++) {
  313. #if NET_2_0
  314. Includes [i].Parent = this;
  315. #endif
  316. XmlSchemaExternal ext = Includes [i] as XmlSchemaExternal;
  317. if (ext == null) {
  318. error (handler, String.Format ("Object of Type {0} is not valid in Includes Property of XmlSchema", Includes [i].GetType().Name));
  319. continue;
  320. }
  321. if (ext.SchemaLocation == null)
  322. continue;
  323. Stream stream = null;
  324. string url = null;
  325. if (resolver != null) {
  326. url = GetResolvedUri (resolver, ext.SchemaLocation);
  327. if (schemaLocationStack.Contains (url)) {
  328. // Just skip nested inclusion.
  329. // The spec is "carefully written"
  330. // not to handle it as an error.
  331. // error (handler, "Nested inclusion was found: " + url);
  332. // must skip this inclusion
  333. continue;
  334. }
  335. if (rootSchema.handledUris.Contains (url))
  336. // This schema is already handled, so simply skip (otherwise, duplicate definition errrors occur.
  337. continue;
  338. rootSchema.handledUris.Add (url, url);
  339. try {
  340. stream = resolver.GetEntity (new Uri (url), null, typeof (Stream)) as Stream;
  341. } catch (Exception) {
  342. // LAMESPEC: This is not good way to handle errors, but since we cannot know what kind of XmlResolver will come, so there are no mean to avoid this ugly catch.
  343. warn (handler, "Could not resolve schema location URI: " + url);
  344. stream = null;
  345. }
  346. }
  347. // Process redefinition children in advance.
  348. XmlSchemaRedefine redefine = Includes [i] as XmlSchemaRedefine;
  349. if (redefine != null) {
  350. for (int j = 0; j < redefine.Items.Count; j++) {
  351. XmlSchemaObject redefinedObj = redefine.Items [j];
  352. redefinedObj.isRedefinedComponent = true;
  353. redefinedObj.isRedefineChild = true;
  354. if (redefinedObj is XmlSchemaType ||
  355. redefinedObj is XmlSchemaGroup ||
  356. redefinedObj is XmlSchemaAttributeGroup)
  357. compilationItems.Add (redefinedObj);
  358. else
  359. error (handler, "Redefinition is only allowed to simpleType, complexType, group and attributeGroup.");
  360. }
  361. }
  362. XmlSchema includedSchema = null;
  363. if (stream == null) {
  364. // It is missing schema components.
  365. missedSubComponents = true;
  366. continue;
  367. } else {
  368. schemaLocationStack.Push (url);
  369. XmlTextReader xtr = null;
  370. try {
  371. xtr = new XmlTextReader (url, stream, nameTable);
  372. includedSchema = XmlSchema.Read (xtr, handler);
  373. } finally {
  374. if (xtr != null)
  375. xtr.Close ();
  376. }
  377. includedSchema.schemas = schemas;
  378. }
  379. // Set - actual - target namespace for the included schema * before compilation*.
  380. XmlSchemaImport import = ext as XmlSchemaImport;
  381. if (import != null) {
  382. if (TargetNamespace == includedSchema.TargetNamespace) {
  383. error (handler, "Target namespace must be different from that of included schema.");
  384. continue;
  385. } else if (includedSchema.TargetNamespace != import.Namespace) {
  386. error (handler, "Attribute namespace and its importing schema's target namespace must be the same.");
  387. continue;
  388. }
  389. } else {
  390. if (TargetNamespace == null &&
  391. includedSchema.TargetNamespace != null) {
  392. error (handler, "Target namespace is required to include a schema which has its own target namespace");
  393. continue;
  394. }
  395. else if (TargetNamespace != null &&
  396. includedSchema.TargetNamespace == null)
  397. includedSchema.TargetNamespace = TargetNamespace;
  398. }
  399. // Compile included schema.
  400. includedSchema.idCollection = this.IDCollection;
  401. includedSchema.Compile (handler, schemaLocationStack, rootSchema, col, resolver);
  402. schemaLocationStack.Pop ();
  403. if (import != null)
  404. rootSchema.schemas.Add (includedSchema);
  405. // Note that we use compiled items. Items
  406. // may not exist in Items, since included
  407. // schema also includes another schemas.
  408. foreach (DictionaryEntry entry in includedSchema.Attributes)
  409. compilationItems.Add ((XmlSchemaObject) entry.Value);
  410. foreach (DictionaryEntry entry in includedSchema.Elements)
  411. compilationItems.Add ((XmlSchemaObject) entry.Value);
  412. foreach (DictionaryEntry entry in includedSchema.SchemaTypes)
  413. compilationItems.Add ((XmlSchemaObject) entry.Value);
  414. foreach (DictionaryEntry entry in includedSchema.AttributeGroups)
  415. compilationItems.Add ((XmlSchemaObject) entry.Value);
  416. foreach (DictionaryEntry entry in includedSchema.Groups)
  417. compilationItems.Add ((XmlSchemaObject) entry.Value);
  418. foreach (DictionaryEntry entry in includedSchema.Notations)
  419. compilationItems.Add ((XmlSchemaObject) entry.Value);
  420. }
  421. // Compilation phase.
  422. // At least each Compile() must gives unique (qualified) name for each component.
  423. // It also checks self-resolvable properties correct.
  424. // Post compilation schema information contribution is not required here.
  425. // It should be done by Validate().
  426. for (int i = 0; i < compilationItems.Count; i++) {
  427. XmlSchemaObject obj = compilationItems [i];
  428. if(obj is XmlSchemaAnnotation) {
  429. int numerr = ((XmlSchemaAnnotation)obj).Compile (handler, this);
  430. errorCount += numerr;
  431. } else if (obj is XmlSchemaAttribute) {
  432. XmlSchemaAttribute attr = (XmlSchemaAttribute) obj;
  433. attr.ParentIsSchema = true;
  434. int numerr = attr.Compile (handler, this);
  435. errorCount += numerr;
  436. if(numerr == 0)
  437. {
  438. XmlSchemaUtil.AddToTable (Attributes, attr, attr.QualifiedName, handler);
  439. }
  440. } else if (obj is XmlSchemaAttributeGroup) {
  441. XmlSchemaAttributeGroup attrgrp = (XmlSchemaAttributeGroup) obj;
  442. int numerr = attrgrp.Compile(handler, this);
  443. errorCount += numerr;
  444. if (numerr == 0)
  445. XmlSchemaUtil.AddToTable (
  446. AttributeGroups,
  447. attrgrp,
  448. attrgrp.QualifiedName,
  449. handler);
  450. } else if (obj is XmlSchemaComplexType) {
  451. XmlSchemaComplexType ctype = (XmlSchemaComplexType) obj;
  452. ctype.ParentIsSchema = true;
  453. int numerr = ctype.Compile (handler, this);
  454. errorCount += numerr;
  455. if (numerr == 0)
  456. XmlSchemaUtil.AddToTable (
  457. schemaTypes,
  458. ctype,
  459. ctype.QualifiedName,
  460. handler);
  461. } else if (obj is XmlSchemaSimpleType) {
  462. XmlSchemaSimpleType stype = (XmlSchemaSimpleType) obj;
  463. stype.islocal = false; //This simple type is toplevel
  464. int numerr = stype.Compile (handler, this);
  465. errorCount += numerr;
  466. if (numerr == 0)
  467. XmlSchemaUtil.AddToTable (
  468. SchemaTypes,
  469. stype,
  470. stype.QualifiedName,
  471. handler);
  472. } else if (obj is XmlSchemaElement) {
  473. XmlSchemaElement elem = (XmlSchemaElement) obj;
  474. elem.parentIsSchema = true;
  475. int numerr = elem.Compile (handler, this);
  476. errorCount += numerr;
  477. if (numerr == 0)
  478. XmlSchemaUtil.AddToTable (
  479. Elements,
  480. elem,
  481. elem.QualifiedName,
  482. handler);
  483. } else if (obj is XmlSchemaGroup) {
  484. XmlSchemaGroup grp = (XmlSchemaGroup) obj;
  485. int numerr = grp.Compile (handler, this);
  486. errorCount += numerr;
  487. if (numerr == 0)
  488. XmlSchemaUtil.AddToTable (
  489. Groups,
  490. grp,
  491. grp.QualifiedName,
  492. handler);
  493. } else if (obj is XmlSchemaNotation) {
  494. XmlSchemaNotation ntn = (XmlSchemaNotation) obj;
  495. int numerr = ntn.Compile (handler, this);
  496. errorCount += numerr;
  497. if (numerr == 0)
  498. XmlSchemaUtil.AddToTable (
  499. Notations,
  500. ntn,
  501. ntn.QualifiedName,
  502. handler);
  503. } else {
  504. ValidationHandler.RaiseValidationEvent (
  505. handler,
  506. null,
  507. String.Format ("Object of Type {0} is not valid in Item Property of Schema", obj.GetType ().Name),
  508. null,
  509. this,
  510. null,
  511. XmlSeverityType.Error);
  512. }
  513. }
  514. if (rootSchema == this)
  515. Validate(handler);
  516. if (errorCount == 0)
  517. isCompiled = true;
  518. errorCount = 0;
  519. }
  520. private string GetResolvedUri (XmlResolver resolver, string relativeUri)
  521. {
  522. Uri baseUri = null;
  523. if (this.SourceUri != null && this.SourceUri != String.Empty)
  524. baseUri = new Uri (this.SourceUri);
  525. Uri abs = resolver.ResolveUri (baseUri, relativeUri);
  526. return abs != null ? abs.ToString () : String.Empty;
  527. }
  528. internal bool IsNamespaceAbsent (string ns)
  529. {
  530. return !schemas.Contains (ns);
  531. }
  532. #endregion
  533. private void Validate (ValidationEventHandler handler)
  534. {
  535. ValidationId = CompilationId;
  536. // Firstly Element needs to be filled their substitution group info
  537. foreach (XmlSchemaElement elem in Elements.Values)
  538. elem.FillSubstitutionElementInfo ();
  539. // Validate
  540. foreach (XmlSchemaAttribute attr in Attributes.Values)
  541. errorCount += attr.Validate (handler, this);
  542. foreach (XmlSchemaAttributeGroup attrgrp in AttributeGroups.Values)
  543. errorCount += attrgrp.Validate (handler, this);
  544. foreach (XmlSchemaType type in SchemaTypes.Values)
  545. errorCount += type.Validate (handler, this);
  546. foreach (XmlSchemaElement elem in Elements.Values)
  547. errorCount += elem.Validate (handler, this);
  548. foreach (XmlSchemaGroup grp in Groups.Values)
  549. errorCount += grp.Validate (handler, this);
  550. foreach (XmlSchemaNotation ntn in Notations.Values)
  551. errorCount += ntn.Validate (handler, this);
  552. }
  553. #region Read
  554. // We cannot use xml deserialization, since it does not provide line info, qname context, and so on.
  555. public static XmlSchema Read (TextReader reader, ValidationEventHandler validationEventHandler)
  556. {
  557. return Read (new XmlTextReader (reader),validationEventHandler);
  558. }
  559. public static XmlSchema Read (Stream stream, ValidationEventHandler validationEventHandler)
  560. {
  561. return Read (new XmlTextReader (stream),validationEventHandler);
  562. }
  563. public static XmlSchema Read (XmlReader rdr, ValidationEventHandler validationEventHandler)
  564. {
  565. XmlSchemaReader reader = new XmlSchemaReader (rdr, validationEventHandler);
  566. if (reader.ReadState == ReadState.Initial)
  567. reader.ReadNextElement ();
  568. int startDepth = reader.Depth;
  569. do
  570. {
  571. switch(reader.NodeType)
  572. {
  573. case XmlNodeType.Element:
  574. if(reader.LocalName == "schema")
  575. {
  576. XmlSchema schema = new XmlSchema ();
  577. schema.nameTable = rdr.NameTable;
  578. schema.LineNumber = reader.LineNumber;
  579. schema.LinePosition = reader.LinePosition;
  580. schema.SourceUri = reader.BaseURI;
  581. ReadAttributes(schema, reader, validationEventHandler);
  582. //IsEmptyElement does not behave properly if reader is
  583. //positioned at an attribute.
  584. reader.MoveToElement();
  585. if(!reader.IsEmptyElement)
  586. {
  587. ReadContent(schema, reader, validationEventHandler);
  588. }
  589. else
  590. rdr.Skip ();
  591. if (rdr.NodeType == XmlNodeType.EndElement)
  592. rdr.Read ();
  593. return schema;
  594. }
  595. else
  596. //Schema can't be generated. Throw an exception
  597. error (validationEventHandler, "The root element must be schema", null);
  598. break;
  599. default:
  600. error(validationEventHandler, "This should never happen. XmlSchema.Read 1 ",null);
  601. break;
  602. }
  603. } while(reader.Depth > startDepth && reader.ReadNextElement());
  604. // This is thrown regardless of ValidationEventHandler existence.
  605. throw new XmlSchemaException ("The top level schema must have namespace " + XmlSchema.Namespace, null);
  606. }
  607. private static void ReadAttributes(XmlSchema schema, XmlSchemaReader reader, ValidationEventHandler h)
  608. {
  609. Exception ex;
  610. reader.MoveToElement();
  611. while(reader.MoveToNextAttribute())
  612. {
  613. switch(reader.Name)
  614. {
  615. case "attributeFormDefault" :
  616. schema.attributeFormDefault = XmlSchemaUtil.ReadFormAttribute(reader,out ex);
  617. if(ex != null)
  618. error(h, reader.Value + " is not a valid value for attributeFormDefault.", ex);
  619. break;
  620. case "blockDefault" :
  621. schema.blockDefault = XmlSchemaUtil.ReadDerivationAttribute(reader,out ex, "blockDefault",
  622. XmlSchemaUtil.ElementBlockAllowed);
  623. if(ex != null)
  624. error (h, ex.Message, ex);
  625. break;
  626. case "elementFormDefault":
  627. schema.elementFormDefault = XmlSchemaUtil.ReadFormAttribute(reader, out ex);
  628. if(ex != null)
  629. error(h, reader.Value + " is not a valid value for elementFormDefault.", ex);
  630. break;
  631. case "finalDefault":
  632. schema.finalDefault = XmlSchemaUtil.ReadDerivationAttribute(reader, out ex, "finalDefault",
  633. XmlSchemaUtil.FinalAllowed);
  634. if(ex != null)
  635. error (h, ex.Message , ex);
  636. break;
  637. case "id":
  638. schema.id = reader.Value;
  639. break;
  640. case "targetNamespace":
  641. schema.targetNamespace = reader.Value;
  642. break;
  643. case "version":
  644. schema.version = reader.Value;
  645. break;
  646. default:
  647. if((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace)
  648. error(h, reader.Name + " attribute is not allowed in schema element",null);
  649. else
  650. {
  651. XmlSchemaUtil.ReadUnhandledAttribute(reader,schema);
  652. }
  653. break;
  654. }
  655. }
  656. }
  657. private static void ReadContent(XmlSchema schema, XmlSchemaReader reader, ValidationEventHandler h)
  658. {
  659. reader.MoveToElement();
  660. if(reader.LocalName != "schema" && reader.NamespaceURI != XmlSchema.Namespace && reader.NodeType != XmlNodeType.Element)
  661. error(h, "UNREACHABLE CODE REACHED: Method: Schema.ReadContent, " + reader.LocalName + ", " + reader.NamespaceURI,null);
  662. //(include | import | redefine | annotation)*,
  663. //((simpleType | complexType | group | attributeGroup | element | attribute | notation | annotation)*
  664. int level = 1;
  665. while(reader.ReadNextElement())
  666. {
  667. if(reader.NodeType == XmlNodeType.EndElement)
  668. {
  669. if(reader.LocalName != xmlname)
  670. error(h,"Should not happen :2: XmlSchema.Read, name="+reader.Name,null);
  671. break;
  672. }
  673. if(level <= 1)
  674. {
  675. if(reader.LocalName == "include")
  676. {
  677. XmlSchemaInclude include = XmlSchemaInclude.Read(reader,h);
  678. if(include != null)
  679. schema.includes.Add(include);
  680. continue;
  681. }
  682. if(reader.LocalName == "import")
  683. {
  684. XmlSchemaImport import = XmlSchemaImport.Read(reader,h);
  685. if(import != null)
  686. schema.includes.Add(import);
  687. continue;
  688. }
  689. if(reader.LocalName == "redefine")
  690. {
  691. XmlSchemaRedefine redefine = XmlSchemaRedefine.Read(reader,h);
  692. if(redefine != null)
  693. schema.includes.Add(redefine);
  694. continue;
  695. }
  696. if(reader.LocalName == "annotation")
  697. {
  698. XmlSchemaAnnotation annotation = XmlSchemaAnnotation.Read(reader,h);
  699. if(annotation != null)
  700. schema.items.Add(annotation);
  701. continue;
  702. }
  703. }
  704. if(level <=2)
  705. {
  706. level = 2;
  707. if(reader.LocalName == "simpleType")
  708. {
  709. XmlSchemaSimpleType stype = XmlSchemaSimpleType.Read(reader,h);
  710. if(stype != null)
  711. schema.items.Add(stype);
  712. continue;
  713. }
  714. if(reader.LocalName == "complexType")
  715. {
  716. XmlSchemaComplexType ctype = XmlSchemaComplexType.Read(reader,h);
  717. if(ctype != null)
  718. schema.items.Add(ctype);
  719. continue;
  720. }
  721. if(reader.LocalName == "group")
  722. {
  723. XmlSchemaGroup group = XmlSchemaGroup.Read(reader,h);
  724. if(group != null)
  725. schema.items.Add(group);
  726. continue;
  727. }
  728. if(reader.LocalName == "attributeGroup")
  729. {
  730. XmlSchemaAttributeGroup attributeGroup = XmlSchemaAttributeGroup.Read(reader,h);
  731. if(attributeGroup != null)
  732. schema.items.Add(attributeGroup);
  733. continue;
  734. }
  735. if(reader.LocalName == "element")
  736. {
  737. XmlSchemaElement element = XmlSchemaElement.Read(reader,h);
  738. if(element != null)
  739. schema.items.Add(element);
  740. continue;
  741. }
  742. if(reader.LocalName == "attribute")
  743. {
  744. XmlSchemaAttribute attr = XmlSchemaAttribute.Read(reader,h);
  745. if(attr != null)
  746. schema.items.Add(attr);
  747. continue;
  748. }
  749. if(reader.LocalName == "notation")
  750. {
  751. XmlSchemaNotation notation = XmlSchemaNotation.Read(reader,h);
  752. if(notation != null)
  753. schema.items.Add(notation);
  754. continue;
  755. }
  756. if(reader.LocalName == "annotation")
  757. {
  758. XmlSchemaAnnotation annotation = XmlSchemaAnnotation.Read(reader,h);
  759. if(annotation != null)
  760. schema.items.Add(annotation);
  761. continue;
  762. }
  763. }
  764. reader.RaiseInvalidElementError();
  765. }
  766. }
  767. #endregion
  768. #region write
  769. public void Write(System.IO.Stream stream)
  770. {
  771. Write(stream,null);
  772. }
  773. public void Write(System.IO.TextWriter writer)
  774. {
  775. Write(writer,null);
  776. }
  777. public void Write(System.Xml.XmlWriter writer)
  778. {
  779. Write(writer,null);
  780. }
  781. public void Write(System.IO.Stream stream, System.Xml.XmlNamespaceManager namespaceManager)
  782. {
  783. Write(new XmlTextWriter(stream,null),namespaceManager);
  784. }
  785. public void Write(System.IO.TextWriter writer, System.Xml.XmlNamespaceManager namespaceManager)
  786. {
  787. XmlTextWriter xwriter = new XmlTextWriter(writer);
  788. xwriter.Formatting = Formatting.Indented;
  789. Write(xwriter,namespaceManager);
  790. }
  791. public void Write (System.Xml.XmlWriter writer, System.Xml.XmlNamespaceManager namespaceManager)
  792. {
  793. XmlSerializerNamespaces nss = new XmlSerializerNamespaces ();
  794. if (namespaceManager != null) {
  795. foreach (string name in namespaceManager) {
  796. //xml and xmlns namespaces are added by default in namespaceManager.
  797. //So we should ignore them
  798. if (name !="xml" && name != "xmlns")
  799. nss.Add (name, namespaceManager.LookupNamespace (name));
  800. }
  801. }
  802. if (Namespaces != null && Namespaces.Count > 0) {
  803. XmlQualifiedName [] qnames = Namespaces.ToArray ();
  804. foreach (XmlQualifiedName qn in qnames)
  805. nss.Add (qn.Name, qn.Namespace);
  806. string p = String.Empty;
  807. bool loop = true;
  808. for (int idx = 1; loop; idx++) {
  809. loop = false;
  810. foreach (XmlQualifiedName qn in qnames)
  811. if (qn.Name == p) {
  812. p = "q" + idx;
  813. loop = true;
  814. break;
  815. }
  816. }
  817. nss.Add (p, XmlSchema.Namespace);
  818. }
  819. if (nss.Count == 0) {
  820. // Add the xml schema namespace. (It is done
  821. // only when no entry exists in Namespaces).
  822. nss.Add ("xs", XmlSchema.Namespace);
  823. if (TargetNamespace != null)
  824. nss.Add ("tns", TargetNamespace);
  825. }
  826. XmlSchemaSerializer xser = new XmlSchemaSerializer ();
  827. XmlSerializerNamespaces backup = Namespaces;
  828. try {
  829. Namespaces = null;
  830. xser.Serialize (writer, this, nss);
  831. } finally {
  832. Namespaces = backup;
  833. }
  834. writer.Flush();
  835. }
  836. #endregion
  837. }
  838. class XmlSchemaSerializer : XmlSerializer
  839. {
  840. protected override void Serialize (object o, XmlSerializationWriter writer)
  841. {
  842. XmlSchemaSerializationWriter w = writer as XmlSchemaSerializationWriter;
  843. w.WriteRoot_XmlSchema ((XmlSchema) o);
  844. }
  845. protected override XmlSerializationWriter CreateWriter ()
  846. {
  847. return new XmlSchemaSerializationWriter ();
  848. }
  849. }
  850. }