XmlSchema.cs 42 KB

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