XmlSchema.cs 29 KB

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