DTDObjectModel.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  1. //
  2. // Mono.Xml.DTDObjectModel
  3. //
  4. // Author:
  5. // Atsushi Enomoto ([email protected])
  6. //
  7. // (C)2003 Atsushi Enomoto
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Collections;
  31. using System.Globalization;
  32. using System.IO;
  33. using System.Text;
  34. using System.Xml;
  35. using System.Xml.Schema;
  36. using Mono.Xml.Schema;
  37. #if NET_2_0
  38. using XmlTextReaderImpl = Mono.Xml2.XmlTextReader;
  39. #else
  40. using XmlTextReaderImpl = System.Xml.XmlTextReader;
  41. #endif
  42. namespace Mono.Xml
  43. {
  44. internal class DTDObjectModel
  45. {
  46. // This specifies the max number of dependent external entities
  47. // per a DTD can consume. A malicious external document server
  48. // might send users' document processing server a large number
  49. // of external entities.
  50. public const int AllowedExternalEntitiesMax = 256;
  51. DTDAutomataFactory factory;
  52. DTDElementAutomata rootAutomata;
  53. DTDEmptyAutomata emptyAutomata;
  54. DTDAnyAutomata anyAutomata;
  55. DTDInvalidAutomata invalidAutomata;
  56. DTDElementDeclarationCollection elementDecls;
  57. DTDAttListDeclarationCollection attListDecls;
  58. DTDParameterEntityDeclarationCollection peDecls;
  59. DTDEntityDeclarationCollection entityDecls;
  60. DTDNotationDeclarationCollection notationDecls;
  61. ArrayList validationErrors;
  62. XmlResolver resolver;
  63. XmlNameTable nameTable;
  64. Hashtable externalResources;
  65. string baseURI;
  66. string name;
  67. string publicId;
  68. string systemId;
  69. string intSubset;
  70. bool intSubsetHasPERef;
  71. bool isStandalone;
  72. int lineNumber;
  73. int linePosition;
  74. public DTDObjectModel (XmlNameTable nameTable)
  75. {
  76. this.nameTable = nameTable;
  77. elementDecls = new DTDElementDeclarationCollection (this);
  78. attListDecls = new DTDAttListDeclarationCollection (this);
  79. entityDecls = new DTDEntityDeclarationCollection (this);
  80. peDecls = new DTDParameterEntityDeclarationCollection (this);
  81. notationDecls = new DTDNotationDeclarationCollection (this);
  82. factory = new DTDAutomataFactory (this);
  83. validationErrors = new ArrayList ();
  84. externalResources = new Hashtable ();
  85. }
  86. public string BaseURI {
  87. get { return baseURI; }
  88. set { baseURI = value; }
  89. }
  90. public bool IsStandalone {
  91. get { return isStandalone; }
  92. set { isStandalone = value; }
  93. }
  94. public string Name {
  95. get { return name; }
  96. set { name = value; }
  97. }
  98. public XmlNameTable NameTable {
  99. get { return nameTable; }
  100. }
  101. public string PublicId {
  102. get { return publicId; }
  103. set { publicId = value; }
  104. }
  105. public string SystemId {
  106. get { return systemId; }
  107. set { systemId = value; }
  108. }
  109. public string InternalSubset {
  110. get { return intSubset; }
  111. set { intSubset = value; }
  112. }
  113. public bool InternalSubsetHasPEReference {
  114. get { return intSubsetHasPERef; }
  115. set { intSubsetHasPERef = value; }
  116. }
  117. public int LineNumber {
  118. get { return lineNumber; }
  119. set { lineNumber = value; }
  120. }
  121. public int LinePosition {
  122. get { return linePosition; }
  123. set { linePosition = value; }
  124. }
  125. internal XmlSchema CreateXsdSchema ()
  126. {
  127. XmlSchema s = new XmlSchema ();
  128. s.SourceUri = BaseURI;
  129. s.LineNumber = LineNumber;
  130. s.LinePosition = LinePosition;
  131. foreach (DTDElementDeclaration el in ElementDecls.Values)
  132. s.Items.Add (el.CreateXsdElement ());
  133. return s;
  134. }
  135. public string ResolveEntity (string name)
  136. {
  137. DTDEntityDeclaration decl = EntityDecls [name]
  138. as DTDEntityDeclaration;
  139. if (decl == null) {
  140. AddError (new XmlSchemaException ("Required entity was not found.",
  141. this.LineNumber, this.LinePosition, null, this.BaseURI, null));
  142. return " ";
  143. }
  144. else
  145. return decl.EntityValue;
  146. }
  147. internal XmlResolver Resolver {
  148. get { return resolver; }
  149. }
  150. public XmlResolver XmlResolver {
  151. set { resolver = value; }
  152. }
  153. internal Hashtable ExternalResources {
  154. get { return externalResources; }
  155. }
  156. public DTDAutomataFactory Factory {
  157. get { return factory; }
  158. }
  159. public DTDElementDeclaration RootElement {
  160. get { return ElementDecls [Name]; }
  161. }
  162. public DTDElementDeclarationCollection ElementDecls {
  163. get { return elementDecls; }
  164. }
  165. public DTDAttListDeclarationCollection AttListDecls {
  166. get { return attListDecls; }
  167. }
  168. public DTDEntityDeclarationCollection EntityDecls {
  169. get { return entityDecls; }
  170. }
  171. public DTDParameterEntityDeclarationCollection PEDecls {
  172. get { return peDecls; }
  173. }
  174. public DTDNotationDeclarationCollection NotationDecls {
  175. get { return notationDecls; }
  176. }
  177. public DTDAutomata RootAutomata {
  178. get {
  179. if (rootAutomata == null)
  180. rootAutomata = new DTDElementAutomata (this, this.Name);
  181. return rootAutomata;
  182. }
  183. }
  184. public DTDEmptyAutomata Empty {
  185. get {
  186. if (emptyAutomata == null)
  187. emptyAutomata = new DTDEmptyAutomata (this);
  188. return emptyAutomata;
  189. }
  190. }
  191. public DTDAnyAutomata Any {
  192. get {
  193. if (anyAutomata == null)
  194. anyAutomata = new DTDAnyAutomata (this);
  195. return anyAutomata;
  196. }
  197. }
  198. public DTDInvalidAutomata Invalid {
  199. get {
  200. if (invalidAutomata == null)
  201. invalidAutomata = new DTDInvalidAutomata (this);
  202. return invalidAutomata;
  203. }
  204. }
  205. public XmlSchemaException [] Errors {
  206. get { return validationErrors.ToArray (typeof (XmlSchemaException)) as XmlSchemaException []; }
  207. }
  208. public void AddError (XmlSchemaException ex)
  209. {
  210. validationErrors.Add (ex);
  211. }
  212. #if NET_2_0
  213. internal string GenerateEntityAttributeText (string entityName)
  214. {
  215. DTDEntityDeclaration entity = EntityDecls [entityName] as DTDEntityDeclaration;
  216. if (entity == null)
  217. return null;
  218. return entity.EntityValue;
  219. }
  220. internal XmlTextReaderImpl GenerateEntityContentReader (string entityName, XmlParserContext context)
  221. {
  222. DTDEntityDeclaration entity = EntityDecls [entityName] as DTDEntityDeclaration;
  223. if (entity == null)
  224. return null;
  225. if (entity.SystemId != null) {
  226. Uri baseUri = entity.BaseURI == String.Empty ? null : new Uri (entity.BaseURI);
  227. Stream stream = resolver.GetEntity (resolver.ResolveUri (baseUri, entity.SystemId), null, typeof (Stream)) as Stream;
  228. return new XmlTextReaderImpl (stream, XmlNodeType.Element, context);
  229. }
  230. else
  231. return new XmlTextReaderImpl (entity.EntityValue, XmlNodeType.Element, context);
  232. }
  233. #endif
  234. }
  235. internal class DTDCollectionBase : DictionaryBase
  236. {
  237. DTDObjectModel root;
  238. protected DTDCollectionBase (DTDObjectModel root)
  239. {
  240. this.root = root;
  241. }
  242. protected DTDObjectModel Root {
  243. get { return root; }
  244. }
  245. public ICollection Keys {
  246. get { return InnerHashtable.Keys; }
  247. }
  248. public ICollection Values {
  249. get { return InnerHashtable.Values; }
  250. }
  251. }
  252. internal class DTDElementDeclarationCollection : DTDCollectionBase
  253. {
  254. public DTDElementDeclarationCollection (DTDObjectModel root) : base (root) {}
  255. public DTDElementDeclaration this [string name] {
  256. get { return Get (name); }
  257. }
  258. public DTDElementDeclaration Get (string name)
  259. {
  260. return InnerHashtable [name] as DTDElementDeclaration;
  261. }
  262. public void Add (string name, DTDElementDeclaration decl)
  263. {
  264. if (InnerHashtable.Contains (name)) {
  265. Root.AddError (new XmlSchemaException (String.Format (
  266. "Element declaration for {0} was already added.",
  267. name), null));
  268. return;
  269. }
  270. decl.SetRoot (Root);
  271. InnerHashtable.Add (name, decl);
  272. }
  273. }
  274. internal class DTDAttListDeclarationCollection : DTDCollectionBase
  275. {
  276. public DTDAttListDeclarationCollection (DTDObjectModel root) : base (root) {}
  277. public DTDAttListDeclaration this [string name] {
  278. get { return InnerHashtable [name] as DTDAttListDeclaration; }
  279. }
  280. public void Add (string name, DTDAttListDeclaration decl)
  281. {
  282. DTDAttListDeclaration existing = this [name];
  283. if (existing != null) {
  284. // It is valid, that is additive declaration.
  285. foreach (DTDAttributeDefinition def in decl.Definitions)
  286. if (decl.Get (def.Name) == null)
  287. existing.Add (def);
  288. } else {
  289. decl.SetRoot (Root);
  290. InnerHashtable.Add (name, decl);
  291. }
  292. }
  293. }
  294. internal class DTDEntityDeclarationCollection : DTDCollectionBase
  295. {
  296. public DTDEntityDeclarationCollection (DTDObjectModel root) : base (root) {}
  297. public DTDEntityDeclaration this [string name] {
  298. get { return InnerHashtable [name] as DTDEntityDeclaration; }
  299. }
  300. public void Add (string name, DTDEntityDeclaration decl)
  301. {
  302. if (InnerHashtable [name] != null)
  303. throw new InvalidOperationException (String.Format (
  304. "Entity declaration for {0} was already added.",
  305. name));
  306. decl.SetRoot (Root);
  307. InnerHashtable.Add (name, decl);
  308. }
  309. }
  310. internal class DTDNotationDeclarationCollection : DTDCollectionBase
  311. {
  312. public DTDNotationDeclarationCollection (DTDObjectModel root) : base (root) {}
  313. public DTDNotationDeclaration this [string name] {
  314. get { return InnerHashtable [name] as DTDNotationDeclaration; }
  315. }
  316. public void Add (string name, DTDNotationDeclaration decl)
  317. {
  318. if (InnerHashtable [name] != null)
  319. throw new InvalidOperationException (String.Format (
  320. "Notation declaration for {0} was already added.",
  321. name));
  322. decl.SetRoot (Root);
  323. InnerHashtable.Add (name, decl);
  324. }
  325. }
  326. // This class contains either ElementName or ChildModels.
  327. internal class DTDContentModel : DTDNode
  328. {
  329. DTDObjectModel root;
  330. DTDAutomata compiledAutomata;
  331. string ownerElementName;
  332. string elementName;
  333. DTDContentOrderType orderType = DTDContentOrderType.None;
  334. DTDContentModelCollection childModels = new DTDContentModelCollection ();
  335. DTDOccurence occurence = DTDOccurence.One;
  336. internal DTDContentModel (DTDObjectModel root, string ownerElementName)
  337. {
  338. this.root = root;
  339. this.ownerElementName = ownerElementName;
  340. }
  341. public DTDContentModelCollection ChildModels {
  342. get { return childModels; }
  343. set { childModels = value; }
  344. }
  345. public DTDElementDeclaration ElementDecl {
  346. get { return root.ElementDecls [ownerElementName]; }
  347. }
  348. public string ElementName {
  349. get { return elementName; }
  350. set { elementName = value; }
  351. }
  352. public DTDOccurence Occurence {
  353. get { return occurence; }
  354. set { occurence = value; }
  355. }
  356. public DTDContentOrderType OrderType {
  357. get { return orderType; }
  358. set { orderType = value; }
  359. }
  360. public DTDAutomata GetAutomata ()
  361. {
  362. if (compiledAutomata == null)
  363. Compile ();
  364. return compiledAutomata;
  365. }
  366. public DTDAutomata Compile ()
  367. {
  368. compiledAutomata = CompileInternal ();
  369. return compiledAutomata;
  370. }
  371. internal XmlSchemaParticle CreateXsdParticle ()
  372. {
  373. XmlSchemaParticle p = null;
  374. if (ElementName != null) {
  375. XmlSchemaElement el = new XmlSchemaElement ();
  376. SetLineInfo (el);
  377. el.RefName = new XmlQualifiedName (ElementName);
  378. return el;
  379. } else {
  380. XmlSchemaGroupBase gb =
  381. (OrderType == DTDContentOrderType.Seq) ?
  382. (XmlSchemaGroupBase)
  383. new XmlSchemaSequence () :
  384. new XmlSchemaChoice ();
  385. SetLineInfo (gb);
  386. foreach (DTDContentModel cm in ChildModels.Items)
  387. gb.Items.Add (cm.CreateXsdParticle ());
  388. p = gb;
  389. }
  390. switch (Occurence) {
  391. case DTDOccurence.Optional:
  392. p.MinOccurs = 0;
  393. break;
  394. case DTDOccurence.OneOrMore:
  395. p.MaxOccursString = "unbounded";
  396. break;
  397. case DTDOccurence.ZeroOrMore:
  398. p.MinOccurs = 0;
  399. p.MaxOccursString = "unbounded";
  400. break;
  401. }
  402. return p;
  403. }
  404. private DTDAutomata CompileInternal ()
  405. {
  406. if (ElementDecl.IsAny)
  407. return root.Any;
  408. if (ElementDecl.IsEmpty)
  409. return root.Empty;
  410. DTDAutomata basis = GetBasicContentAutomata ();
  411. switch (Occurence) {
  412. case DTDOccurence.One:
  413. return basis;
  414. case DTDOccurence.Optional:
  415. return Choice (root.Empty, basis);
  416. case DTDOccurence.OneOrMore:
  417. return new DTDOneOrMoreAutomata (root, basis);
  418. case DTDOccurence.ZeroOrMore:
  419. return Choice (root.Empty, new DTDOneOrMoreAutomata (root, basis));
  420. }
  421. throw new InvalidOperationException ();
  422. }
  423. private DTDAutomata GetBasicContentAutomata ()
  424. {
  425. if (ElementName != null)
  426. return new DTDElementAutomata (root, ElementName);
  427. switch (ChildModels.Count) {
  428. case 0:
  429. return root.Empty;
  430. case 1:
  431. return ChildModels [0].GetAutomata ();
  432. }
  433. DTDAutomata current = null;
  434. int childCount = ChildModels.Count;
  435. switch (OrderType) {
  436. case DTDContentOrderType.Seq:
  437. current = Sequence (
  438. ChildModels [childCount - 2].GetAutomata (),
  439. ChildModels [childCount - 1].GetAutomata ());
  440. for (int i = childCount - 2; i > 0; i--)
  441. current = Sequence (
  442. ChildModels [i - 1].GetAutomata (), current);
  443. return current;
  444. case DTDContentOrderType.Or:
  445. current = Choice (
  446. ChildModels [childCount - 2].GetAutomata (),
  447. ChildModels [childCount - 1].GetAutomata ());
  448. for (int i = childCount - 2; i > 0; i--)
  449. current = Choice (
  450. ChildModels [i - 1].GetAutomata (), current);
  451. return current;
  452. default:
  453. throw new InvalidOperationException ("Invalid pattern specification");
  454. }
  455. }
  456. private DTDAutomata Sequence (DTDAutomata l, DTDAutomata r)
  457. {
  458. return root.Factory.Sequence (l, r);
  459. }
  460. private DTDAutomata Choice (DTDAutomata l, DTDAutomata r)
  461. {
  462. return l.MakeChoice (r);
  463. }
  464. }
  465. internal class DTDContentModelCollection
  466. {
  467. ArrayList contentModel = new ArrayList ();
  468. public DTDContentModelCollection ()
  469. {
  470. }
  471. public IList Items {
  472. get { return contentModel; }
  473. }
  474. public DTDContentModel this [int i] {
  475. get { return contentModel [i] as DTDContentModel; }
  476. }
  477. public int Count {
  478. get { return contentModel.Count; }
  479. }
  480. public void Add (DTDContentModel model)
  481. {
  482. contentModel.Add (model);
  483. }
  484. }
  485. internal abstract class DTDNode : IXmlLineInfo
  486. {
  487. DTDObjectModel root;
  488. bool isInternalSubset;
  489. string baseURI;
  490. int lineNumber;
  491. int linePosition;
  492. public virtual string BaseURI {
  493. get { return baseURI; }
  494. set { baseURI = value; }
  495. }
  496. public bool IsInternalSubset {
  497. get { return isInternalSubset; }
  498. set { isInternalSubset = value; }
  499. }
  500. public int LineNumber {
  501. get { return lineNumber; }
  502. set { lineNumber = value; }
  503. }
  504. public int LinePosition {
  505. get { return linePosition; }
  506. set { linePosition = value; }
  507. }
  508. public bool HasLineInfo ()
  509. {
  510. return lineNumber != 0;
  511. }
  512. internal void SetRoot (DTDObjectModel root)
  513. {
  514. this.root = root;
  515. if (baseURI == null)
  516. this.BaseURI = root.BaseURI;
  517. }
  518. protected DTDObjectModel Root {
  519. get { return root; }
  520. }
  521. internal XmlException NotWFError (string message)
  522. {
  523. return new XmlException (this as IXmlLineInfo, BaseURI, message);
  524. }
  525. public void SetLineInfo (XmlSchemaObject obj)
  526. {
  527. obj.SourceUri = BaseURI;
  528. obj.LineNumber = LineNumber;
  529. obj.LinePosition = LinePosition;
  530. }
  531. }
  532. internal class DTDElementDeclaration : DTDNode
  533. {
  534. DTDObjectModel root;
  535. DTDContentModel contentModel;
  536. string name;
  537. bool isEmpty;
  538. bool isAny;
  539. bool isMixedContent;
  540. internal DTDElementDeclaration (DTDObjectModel root)
  541. {
  542. this.root = root;
  543. }
  544. public string Name {
  545. get { return name; }
  546. set { name = value; }
  547. }
  548. public bool IsEmpty {
  549. get { return isEmpty; }
  550. set { isEmpty = value; }
  551. }
  552. public bool IsAny {
  553. get { return isAny; }
  554. set { isAny = value; }
  555. }
  556. public bool IsMixedContent {
  557. get { return isMixedContent; }
  558. set { isMixedContent = value; }
  559. }
  560. public DTDContentModel ContentModel {
  561. get {
  562. if (contentModel == null)
  563. contentModel = new DTDContentModel (root, Name);
  564. return contentModel;
  565. }
  566. }
  567. public DTDAttListDeclaration Attributes {
  568. get {
  569. return Root.AttListDecls [Name];
  570. }
  571. }
  572. internal XmlSchemaElement CreateXsdElement ()
  573. {
  574. XmlSchemaElement el = new XmlSchemaElement ();
  575. SetLineInfo (el);
  576. el.Name = Name;
  577. if (IsEmpty) {
  578. el.SchemaType = new XmlSchemaComplexType ();
  579. SetLineInfo (el.SchemaType);
  580. }
  581. else if (IsAny)
  582. el.SchemaTypeName = new XmlQualifiedName (
  583. "anyType", XmlSchema.Namespace);
  584. else {
  585. XmlSchemaComplexType ct = new XmlSchemaComplexType ();
  586. SetLineInfo (ct);
  587. if (Attributes != null)
  588. foreach (DTDAttributeDefinition a in
  589. Attributes.Definitions)
  590. ct.Attributes.Add (a.CreateXsdAttribute ());
  591. if (IsMixedContent)
  592. ct.IsMixed = true;
  593. ct.Particle = ContentModel.CreateXsdParticle ();
  594. el.SchemaType = ct;
  595. }
  596. return el;
  597. }
  598. }
  599. internal class DTDAttributeDefinition : DTDNode
  600. {
  601. string name;
  602. XmlSchemaDatatype datatype;
  603. ArrayList enumeratedLiterals;
  604. string unresolvedDefault;
  605. ArrayList enumeratedNotations;
  606. DTDAttributeOccurenceType occurenceType = DTDAttributeOccurenceType.None;
  607. string resolvedDefaultValue;
  608. string resolvedNormalizedDefaultValue;
  609. internal DTDAttributeDefinition (DTDObjectModel root)
  610. {
  611. this.SetRoot (root);
  612. }
  613. public string Name {
  614. get { return name; }
  615. set { name =value; }
  616. }
  617. public XmlSchemaDatatype Datatype {
  618. get { return datatype; }
  619. set { datatype = value; }
  620. }
  621. public DTDAttributeOccurenceType OccurenceType {
  622. get { return this.occurenceType; }
  623. set { this.occurenceType = value; }
  624. }
  625. // entity reference inside enumerated values are not allowed,
  626. // but on the other hand, they are allowed inside default value.
  627. // Then I decided to use string ArrayList for enumerated values,
  628. // and unresolved string value for DefaultValue.
  629. public ArrayList EnumeratedAttributeDeclaration {
  630. get {
  631. if (enumeratedLiterals == null)
  632. enumeratedLiterals = new ArrayList ();
  633. return this.enumeratedLiterals;
  634. }
  635. }
  636. public ArrayList EnumeratedNotations {
  637. get {
  638. if (enumeratedNotations == null)
  639. enumeratedNotations = new ArrayList ();
  640. return this.enumeratedNotations;
  641. }
  642. }
  643. public string DefaultValue {
  644. get {
  645. if (resolvedDefaultValue == null)
  646. resolvedDefaultValue = ComputeDefaultValue ();
  647. return resolvedDefaultValue;
  648. }
  649. }
  650. public string NormalizedDefaultValue {
  651. get {
  652. if (resolvedNormalizedDefaultValue == null) {
  653. string s = ComputeDefaultValue ();
  654. try {
  655. object o = Datatype.ParseValue (s, null, null);
  656. resolvedNormalizedDefaultValue =
  657. (o is string []) ?
  658. String.Join (" ", (string []) o) :
  659. o is IFormattable ? ((IFormattable) o).ToString (null, CultureInfo.InvariantCulture) : o.ToString ();
  660. } catch (Exception) {
  661. // This is for non-error-reporting reader
  662. resolvedNormalizedDefaultValue = Datatype.Normalize (s);
  663. }
  664. }
  665. return resolvedNormalizedDefaultValue;
  666. }
  667. }
  668. public string UnresolvedDefaultValue {
  669. get { return this.unresolvedDefault; }
  670. set { this.unresolvedDefault = value; }
  671. }
  672. public char QuoteChar {
  673. get {
  674. return UnresolvedDefaultValue.Length > 0 ?
  675. this.UnresolvedDefaultValue [0] :
  676. '"';
  677. }
  678. }
  679. internal XmlSchemaAttribute CreateXsdAttribute ()
  680. {
  681. XmlSchemaAttribute a = new XmlSchemaAttribute ();
  682. SetLineInfo (a);
  683. a.Name = Name;
  684. a.DefaultValue = resolvedNormalizedDefaultValue;
  685. XmlQualifiedName qname = XmlQualifiedName.Empty;
  686. ArrayList enumeration = null;
  687. if (enumeratedNotations != null && enumeratedNotations.Count > 0) {
  688. qname = new XmlQualifiedName ("NOTATION", XmlSchema.Namespace);
  689. enumeration = enumeratedNotations;
  690. }
  691. else if (enumeratedLiterals != null)
  692. enumeration = enumeratedLiterals;
  693. else {
  694. switch (Datatype.TokenizedType) {
  695. case XmlTokenizedType.ID:
  696. qname = new XmlQualifiedName ("ID", XmlSchema.Namespace); break;
  697. case XmlTokenizedType.IDREF:
  698. qname = new XmlQualifiedName ("IDREF", XmlSchema.Namespace); break;
  699. case XmlTokenizedType.IDREFS:
  700. qname = new XmlQualifiedName ("IDREFS", XmlSchema.Namespace); break;
  701. case XmlTokenizedType.ENTITY:
  702. qname = new XmlQualifiedName ("ENTITY", XmlSchema.Namespace); break;
  703. case XmlTokenizedType.ENTITIES:
  704. qname = new XmlQualifiedName ("ENTITIES", XmlSchema.Namespace); break;
  705. case XmlTokenizedType.NMTOKEN:
  706. qname = new XmlQualifiedName ("NMTOKEN", XmlSchema.Namespace); break;
  707. case XmlTokenizedType.NMTOKENS:
  708. qname = new XmlQualifiedName ("NMTOKENS", XmlSchema.Namespace); break;
  709. case XmlTokenizedType.NOTATION:
  710. qname = new XmlQualifiedName ("NOTATION", XmlSchema.Namespace); break;
  711. }
  712. }
  713. if (enumeration != null) {
  714. XmlSchemaSimpleType st = new XmlSchemaSimpleType ();
  715. SetLineInfo (st);
  716. XmlSchemaSimpleTypeRestriction r =
  717. new XmlSchemaSimpleTypeRestriction ();
  718. SetLineInfo (r);
  719. r.BaseTypeName = qname;
  720. if (enumeratedNotations != null) {
  721. foreach (string name in enumeratedNotations) {
  722. XmlSchemaEnumerationFacet f =
  723. new XmlSchemaEnumerationFacet ();
  724. SetLineInfo (f);
  725. r.Facets.Add (f);
  726. f.Value = name;
  727. }
  728. }
  729. }
  730. else if (qname != XmlQualifiedName.Empty)
  731. a.SchemaTypeName = qname;
  732. return a;
  733. }
  734. internal string ComputeDefaultValue ()
  735. {
  736. if (UnresolvedDefaultValue == null)
  737. return null;
  738. StringBuilder sb = new StringBuilder ();
  739. int pos = 0;
  740. int next = 0;
  741. string value = this.UnresolvedDefaultValue;
  742. while ((next = value.IndexOf ('&', pos)) >= 0) {
  743. int semicolon = value.IndexOf (';', next);
  744. if (value [next + 1] == '#') {
  745. // character reference.
  746. char c = value [next + 2];
  747. NumberStyles style = NumberStyles.Integer;
  748. string spec;
  749. if (c == 'x' || c == 'X') {
  750. spec = value.Substring (next + 3, semicolon - next - 3);
  751. style |= NumberStyles.HexNumber;
  752. }
  753. else
  754. spec = value.Substring (next + 2, semicolon - next - 2);
  755. sb.Append ((char) int.Parse (spec, style, CultureInfo.InvariantCulture));
  756. } else {
  757. sb.Append (value.Substring (pos, next - 1));
  758. string name = value.Substring (next + 1, semicolon - 2);
  759. int predefined = XmlChar.GetPredefinedEntity (name);
  760. if (predefined >= 0)
  761. sb.Append (predefined);
  762. else
  763. sb.Append (Root.ResolveEntity (name));
  764. }
  765. pos = semicolon + 1;
  766. }
  767. sb.Append (value.Substring (pos));
  768. // strip quote chars
  769. string ret = sb.ToString (1, sb.Length - 2);
  770. sb.Length = 0;
  771. return ret;
  772. }
  773. }
  774. internal class DTDAttListDeclaration : DTDNode
  775. {
  776. string name;
  777. Hashtable attributeOrders = new Hashtable ();
  778. ArrayList attributes = new ArrayList ();
  779. internal DTDAttListDeclaration (DTDObjectModel root)
  780. {
  781. SetRoot (root);
  782. }
  783. public string Name {
  784. get { return name; }
  785. set { name = value; }
  786. }
  787. public DTDAttributeDefinition this [int i] {
  788. get { return Get (i); }
  789. }
  790. public DTDAttributeDefinition this [string name] {
  791. get { return Get (name); }
  792. }
  793. public DTDAttributeDefinition Get (int i)
  794. {
  795. return attributes [i] as DTDAttributeDefinition;
  796. }
  797. public DTDAttributeDefinition Get (string name)
  798. {
  799. object o = attributeOrders [name];
  800. if (o != null)
  801. return attributes [(int) o] as DTDAttributeDefinition;
  802. else
  803. return null;
  804. }
  805. public IList Definitions {
  806. get { return attributes; }
  807. }
  808. public void Add (DTDAttributeDefinition def)
  809. {
  810. if (attributeOrders [def.Name] != null)
  811. throw new InvalidOperationException (String.Format (
  812. "Attribute definition for {0} was already added at element {1}.",
  813. def.Name, this.Name));
  814. def.SetRoot (Root);
  815. attributeOrders.Add (def.Name, attributes.Count);
  816. attributes.Add (def);
  817. }
  818. public int Count {
  819. get { return attributeOrders.Count; }
  820. }
  821. }
  822. internal class DTDEntityBase : DTDNode
  823. {
  824. string name;
  825. string publicId;
  826. string systemId;
  827. string literalValue;
  828. string replacementText;
  829. string uriString;
  830. Uri absUri;
  831. bool isInvalid;
  832. // Exception loadException;
  833. bool loadFailed;
  834. XmlResolver resolver;
  835. protected DTDEntityBase (DTDObjectModel root)
  836. {
  837. SetRoot (root);
  838. }
  839. internal bool IsInvalid {
  840. get { return isInvalid; }
  841. set { isInvalid = value; }
  842. }
  843. public bool LoadFailed {
  844. get { return loadFailed; }
  845. set { loadFailed = value; }
  846. }
  847. public string Name {
  848. get { return name; }
  849. set { name = value; }
  850. }
  851. public string PublicId {
  852. get { return publicId; }
  853. set { publicId = value; }
  854. }
  855. public string SystemId {
  856. get { return systemId; }
  857. set { systemId = value; }
  858. }
  859. public string LiteralEntityValue {
  860. get { return literalValue; }
  861. set { literalValue = value; }
  862. }
  863. public string ReplacementText {
  864. get { return replacementText; }
  865. set { replacementText = value; }
  866. }
  867. public XmlResolver XmlResolver {
  868. set { resolver = value; }
  869. }
  870. public string ActualUri {
  871. get {
  872. if (uriString == null) {
  873. if (resolver == null || SystemId == null || SystemId.Length == 0)
  874. uriString = BaseURI;
  875. else {
  876. Uri baseUri = null;
  877. try {
  878. if (BaseURI != null && BaseURI.Length > 0)
  879. baseUri = new Uri (BaseURI);
  880. } catch (UriFormatException) {
  881. }
  882. absUri = resolver.ResolveUri (baseUri, SystemId);
  883. uriString = absUri != null ? absUri.ToString () : String.Empty;
  884. }
  885. }
  886. return uriString;
  887. }
  888. }
  889. public void Resolve ()
  890. {
  891. if (ActualUri == String.Empty) {
  892. LoadFailed = true;
  893. LiteralEntityValue = String.Empty;
  894. return;
  895. }
  896. if (Root.ExternalResources.ContainsKey (ActualUri))
  897. LiteralEntityValue = (string) Root.ExternalResources [ActualUri];
  898. Stream s = null;
  899. try {
  900. s = resolver.GetEntity (absUri, null, typeof (Stream)) as Stream;
  901. XmlTextReaderImpl xtr = new XmlTextReaderImpl (ActualUri, s, Root.NameTable);
  902. // Don't skip Text declaration here. LiteralEntityValue contains it. See spec 4.5
  903. LiteralEntityValue = xtr.GetRemainder ().ReadToEnd ();
  904. Root.ExternalResources.Add (ActualUri, LiteralEntityValue);
  905. if (Root.ExternalResources.Count > DTDObjectModel.AllowedExternalEntitiesMax)
  906. throw new InvalidOperationException ("The total amount of external entities exceeded the allowed number.");
  907. } catch (Exception ex) {
  908. // loadException = ex;
  909. LiteralEntityValue = String.Empty;
  910. LoadFailed = true;
  911. // throw NotWFError ("Cannot resolve external entity. URI is " + ActualUri + " .");
  912. } finally {
  913. if (s != null)
  914. s.Close ();
  915. }
  916. }
  917. }
  918. internal class DTDEntityDeclaration : DTDEntityBase
  919. {
  920. string entityValue;
  921. string notationName;
  922. ArrayList ReferencingEntities = new ArrayList ();
  923. bool scanned;
  924. bool recursed;
  925. bool hasExternalReference;
  926. internal DTDEntityDeclaration (DTDObjectModel root) : base (root)
  927. {
  928. }
  929. public string NotationName {
  930. get { return notationName; }
  931. set { notationName = value; }
  932. }
  933. public bool HasExternalReference {
  934. get {
  935. if (!scanned)
  936. ScanEntityValue (new ArrayList ());
  937. return hasExternalReference;
  938. }
  939. }
  940. public string EntityValue {
  941. get {
  942. if (this.IsInvalid)
  943. return String.Empty;
  944. if (PublicId == null && SystemId == null && LiteralEntityValue == null)
  945. return String.Empty;
  946. if (entityValue == null) {
  947. if (NotationName != null)
  948. entityValue = "";
  949. else if (SystemId == null || SystemId == String.Empty) {
  950. entityValue = ReplacementText;
  951. if (entityValue == null)
  952. entityValue = String.Empty;
  953. } else {
  954. entityValue = ReplacementText;
  955. }
  956. // Check illegal recursion.
  957. ScanEntityValue (new ArrayList ());
  958. }
  959. return entityValue;
  960. }
  961. }
  962. // It returns whether the entity contains references to external entities.
  963. public void ScanEntityValue (ArrayList refs)
  964. {
  965. // To modify this code, beware nesting between this and EntityValue.
  966. string value = EntityValue;
  967. if (this.SystemId != null)
  968. hasExternalReference = true;
  969. if (recursed)
  970. throw NotWFError ("Entity recursion was found.");
  971. recursed = true;
  972. if (scanned) {
  973. foreach (string referenced in refs)
  974. if (this.ReferencingEntities.Contains (referenced))
  975. throw NotWFError (String.Format (
  976. "Nested entity was found between {0} and {1}",
  977. referenced, Name));
  978. recursed = false;
  979. return;
  980. }
  981. int len = value.Length;
  982. int start = 0;
  983. for (int i=0; i<len; i++) {
  984. switch (value [i]) {
  985. case '&':
  986. start = i+1;
  987. break;
  988. case ';':
  989. if (start == 0)
  990. break;
  991. string name = value.Substring (start, i - start);
  992. if (name.Length == 0)
  993. throw NotWFError ("Entity reference name is missing.");
  994. if (name [0] == '#')
  995. break; // character reference
  996. if (XmlChar.GetPredefinedEntity (name) >= 0)
  997. break; // predefined reference
  998. this.ReferencingEntities.Add (name);
  999. DTDEntityDeclaration decl = Root.EntityDecls [name];
  1000. if (decl != null) {
  1001. if (decl.SystemId != null)
  1002. hasExternalReference = true;
  1003. refs.Add (Name);
  1004. decl.ScanEntityValue (refs);
  1005. foreach (string str in decl.ReferencingEntities)
  1006. ReferencingEntities.Add (str);
  1007. refs.Remove (Name);
  1008. value = value.Remove (start - 1, name.Length + 2);
  1009. value = value.Insert (start - 1, decl.EntityValue);
  1010. i -= name.Length + 1; // not +2, because of immediate i++ .
  1011. len = value.Length;
  1012. }
  1013. start = 0;
  1014. break;
  1015. }
  1016. }
  1017. if (start != 0)
  1018. Root.AddError (new XmlSchemaException ("Invalid reference character '&' is specified.",
  1019. this.LineNumber, this.LinePosition, null, this.BaseURI, null));
  1020. scanned = true;
  1021. recursed = false;
  1022. }
  1023. }
  1024. internal class DTDNotationDeclaration : DTDNode
  1025. {
  1026. string name;
  1027. string localName;
  1028. string prefix;
  1029. string publicId;
  1030. string systemId;
  1031. public string Name {
  1032. get { return name; }
  1033. set { name = value; }
  1034. }
  1035. public string PublicId {
  1036. get { return publicId; }
  1037. set { publicId = value; }
  1038. }
  1039. public string SystemId {
  1040. get { return systemId; }
  1041. set { systemId = value; }
  1042. }
  1043. public string LocalName {
  1044. get { return localName; }
  1045. set { localName = value; }
  1046. }
  1047. public string Prefix {
  1048. get { return prefix; }
  1049. set { prefix = value; }
  1050. }
  1051. internal DTDNotationDeclaration (DTDObjectModel root)
  1052. {
  1053. SetRoot (root);
  1054. }
  1055. }
  1056. internal class DTDParameterEntityDeclarationCollection
  1057. {
  1058. Hashtable peDecls = new Hashtable ();
  1059. DTDObjectModel root;
  1060. public DTDParameterEntityDeclarationCollection (DTDObjectModel root)
  1061. {
  1062. this.root = root;
  1063. }
  1064. public DTDParameterEntityDeclaration this [string name] {
  1065. get { return peDecls [name] as DTDParameterEntityDeclaration; }
  1066. }
  1067. public void Add (string name, DTDParameterEntityDeclaration decl)
  1068. {
  1069. // PEDecl can be overriden.
  1070. if (peDecls [name] != null)
  1071. return;
  1072. decl.SetRoot (root);
  1073. peDecls.Add (name, decl);
  1074. }
  1075. public ICollection Keys {
  1076. get { return peDecls.Keys; }
  1077. }
  1078. public ICollection Values {
  1079. get { return peDecls.Values; }
  1080. }
  1081. }
  1082. internal class DTDParameterEntityDeclaration : DTDEntityBase
  1083. {
  1084. internal DTDParameterEntityDeclaration (DTDObjectModel root) : base (root)
  1085. {
  1086. }
  1087. }
  1088. internal enum DTDContentOrderType
  1089. {
  1090. None,
  1091. Seq,
  1092. Or
  1093. }
  1094. internal enum DTDAttributeOccurenceType
  1095. {
  1096. None,
  1097. Required,
  1098. Optional,
  1099. Fixed
  1100. }
  1101. internal enum DTDOccurence
  1102. {
  1103. One,
  1104. Optional,
  1105. ZeroOrMore,
  1106. OneOrMore
  1107. }
  1108. }