DTDObjectModel.cs 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262
  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. bool isInvalid;
  830. // Exception loadException;
  831. bool loadFailed;
  832. protected DTDEntityBase (DTDObjectModel root)
  833. {
  834. SetRoot (root);
  835. }
  836. internal bool IsInvalid {
  837. get { return isInvalid; }
  838. set { isInvalid = value; }
  839. }
  840. public bool LoadFailed {
  841. get { return loadFailed; }
  842. set { loadFailed = value; }
  843. }
  844. public string Name {
  845. get { return name; }
  846. set { name = value; }
  847. }
  848. public string PublicId {
  849. get { return publicId; }
  850. set { publicId = value; }
  851. }
  852. public string SystemId {
  853. get { return systemId; }
  854. set { systemId = value; }
  855. }
  856. public string LiteralEntityValue {
  857. get { return literalValue; }
  858. set { literalValue = value; }
  859. }
  860. public string ReplacementText {
  861. get { return replacementText; }
  862. set { replacementText = value; }
  863. }
  864. public void Resolve (XmlResolver resolver)
  865. {
  866. if (resolver == null || SystemId == null || SystemId.Length == 0) {
  867. LoadFailed = true;
  868. LiteralEntityValue = String.Empty;
  869. return;
  870. }
  871. Uri baseUri = null;
  872. try {
  873. if (BaseURI != null && BaseURI.Length > 0)
  874. baseUri = new Uri (BaseURI);
  875. } catch (UriFormatException) {
  876. }
  877. Uri absUri = resolver.ResolveUri (baseUri, SystemId);
  878. string absPath = absUri != null ? absUri.ToString () : String.Empty;
  879. if (Root.ExternalResources.ContainsKey (absPath))
  880. LiteralEntityValue = (string) Root.ExternalResources [absPath];
  881. Stream s = null;
  882. try {
  883. s = resolver.GetEntity (absUri, null, typeof (Stream)) as Stream;
  884. XmlTextReaderImpl xtr = new XmlTextReaderImpl (absPath, s, Root.NameTable);
  885. // Don't skip Text declaration here. LiteralEntityValue contains it. See spec 4.5
  886. LiteralEntityValue = xtr.GetRemainder ().ReadToEnd ();
  887. Root.ExternalResources.Add (absPath, LiteralEntityValue);
  888. if (Root.ExternalResources.Count > DTDObjectModel.AllowedExternalEntitiesMax)
  889. throw new InvalidOperationException ("The total amount of external entities exceeded the allowed number.");
  890. } catch (Exception ex) {
  891. // loadException = ex;
  892. LiteralEntityValue = String.Empty;
  893. LoadFailed = true;
  894. // throw NotWFError ("Cannot resolve external entity. URI is " + absPath + " .");
  895. } finally {
  896. if (s != null)
  897. s.Close ();
  898. }
  899. }
  900. }
  901. internal class DTDEntityDeclaration : DTDEntityBase
  902. {
  903. string entityValue;
  904. string notationName;
  905. ArrayList ReferencingEntities = new ArrayList ();
  906. bool scanned;
  907. bool recursed;
  908. bool hasExternalReference;
  909. internal DTDEntityDeclaration (DTDObjectModel root) : base (root)
  910. {
  911. }
  912. public string NotationName {
  913. get { return notationName; }
  914. set { notationName = value; }
  915. }
  916. public bool HasExternalReference {
  917. get {
  918. if (!scanned)
  919. ScanEntityValue (new ArrayList ());
  920. return hasExternalReference;
  921. }
  922. }
  923. public string EntityValue {
  924. get {
  925. if (this.IsInvalid)
  926. return String.Empty;
  927. if (PublicId == null && SystemId == null && LiteralEntityValue == null)
  928. return String.Empty;
  929. if (entityValue == null) {
  930. if (NotationName != null)
  931. entityValue = "";
  932. else if (SystemId == null || SystemId == String.Empty) {
  933. entityValue = ReplacementText;
  934. if (entityValue == null)
  935. entityValue = String.Empty;
  936. } else {
  937. entityValue = ReplacementText;
  938. }
  939. // Check illegal recursion.
  940. ScanEntityValue (new ArrayList ());
  941. }
  942. return entityValue;
  943. }
  944. }
  945. // It returns whether the entity contains references to external entities.
  946. public void ScanEntityValue (ArrayList refs)
  947. {
  948. // To modify this code, beware nesting between this and EntityValue.
  949. string value = EntityValue;
  950. if (this.SystemId != null)
  951. hasExternalReference = true;
  952. if (recursed)
  953. throw NotWFError ("Entity recursion was found.");
  954. recursed = true;
  955. if (scanned) {
  956. foreach (string referenced in refs)
  957. if (this.ReferencingEntities.Contains (referenced))
  958. throw NotWFError (String.Format (
  959. "Nested entity was found between {0} and {1}",
  960. referenced, Name));
  961. recursed = false;
  962. return;
  963. }
  964. int len = value.Length;
  965. int start = 0;
  966. for (int i=0; i<len; i++) {
  967. switch (value [i]) {
  968. case '&':
  969. start = i+1;
  970. break;
  971. case ';':
  972. if (start == 0)
  973. break;
  974. string name = value.Substring (start, i - start);
  975. if (name.Length == 0)
  976. throw NotWFError ("Entity reference name is missing.");
  977. if (name [0] == '#')
  978. break; // character reference
  979. if (XmlChar.GetPredefinedEntity (name) >= 0)
  980. break; // predefined reference
  981. this.ReferencingEntities.Add (name);
  982. DTDEntityDeclaration decl = Root.EntityDecls [name];
  983. if (decl != null) {
  984. if (decl.SystemId != null)
  985. hasExternalReference = true;
  986. refs.Add (Name);
  987. decl.ScanEntityValue (refs);
  988. foreach (string str in decl.ReferencingEntities)
  989. ReferencingEntities.Add (str);
  990. refs.Remove (Name);
  991. value = value.Remove (start - 1, name.Length + 2);
  992. value = value.Insert (start - 1, decl.EntityValue);
  993. i -= name.Length + 1; // not +2, because of immediate i++ .
  994. len = value.Length;
  995. }
  996. start = 0;
  997. break;
  998. }
  999. }
  1000. if (start != 0)
  1001. Root.AddError (new XmlSchemaException ("Invalid reference character '&' is specified.",
  1002. this.LineNumber, this.LinePosition, null, this.BaseURI, null));
  1003. scanned = true;
  1004. recursed = false;
  1005. }
  1006. }
  1007. internal class DTDNotationDeclaration : DTDNode
  1008. {
  1009. string name;
  1010. string localName;
  1011. string prefix;
  1012. string publicId;
  1013. string systemId;
  1014. public string Name {
  1015. get { return name; }
  1016. set { name = value; }
  1017. }
  1018. public string PublicId {
  1019. get { return publicId; }
  1020. set { publicId = value; }
  1021. }
  1022. public string SystemId {
  1023. get { return systemId; }
  1024. set { systemId = value; }
  1025. }
  1026. public string LocalName {
  1027. get { return localName; }
  1028. set { localName = value; }
  1029. }
  1030. public string Prefix {
  1031. get { return prefix; }
  1032. set { prefix = value; }
  1033. }
  1034. internal DTDNotationDeclaration (DTDObjectModel root)
  1035. {
  1036. SetRoot (root);
  1037. }
  1038. }
  1039. internal class DTDParameterEntityDeclarationCollection
  1040. {
  1041. Hashtable peDecls = new Hashtable ();
  1042. DTDObjectModel root;
  1043. public DTDParameterEntityDeclarationCollection (DTDObjectModel root)
  1044. {
  1045. this.root = root;
  1046. }
  1047. public DTDParameterEntityDeclaration this [string name] {
  1048. get { return peDecls [name] as DTDParameterEntityDeclaration; }
  1049. }
  1050. public void Add (string name, DTDParameterEntityDeclaration decl)
  1051. {
  1052. // PEDecl can be overriden.
  1053. if (peDecls [name] != null)
  1054. return;
  1055. decl.SetRoot (root);
  1056. peDecls.Add (name, decl);
  1057. }
  1058. public ICollection Keys {
  1059. get { return peDecls.Keys; }
  1060. }
  1061. public ICollection Values {
  1062. get { return peDecls.Values; }
  1063. }
  1064. }
  1065. internal class DTDParameterEntityDeclaration : DTDEntityBase
  1066. {
  1067. internal DTDParameterEntityDeclaration (DTDObjectModel root) : base (root)
  1068. {
  1069. }
  1070. }
  1071. internal enum DTDContentOrderType
  1072. {
  1073. None,
  1074. Seq,
  1075. Or
  1076. }
  1077. internal enum DTDAttributeOccurenceType
  1078. {
  1079. None,
  1080. Required,
  1081. Optional,
  1082. Fixed
  1083. }
  1084. internal enum DTDOccurence
  1085. {
  1086. One,
  1087. Optional,
  1088. ZeroOrMore,
  1089. OneOrMore
  1090. }
  1091. }