XmlSchema.cs 43 KB

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