XmlSchema.cs 29 KB

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