XmlSchema.cs 43 KB

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