DTDObjectModel.cs 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322
  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 = CreateXsdParticleCore ();
  374. if (p == null)
  375. return null;
  376. switch (Occurence) {
  377. case DTDOccurence.Optional:
  378. p.MinOccurs = 0;
  379. break;
  380. case DTDOccurence.OneOrMore:
  381. p.MaxOccursString = "unbounded";
  382. break;
  383. case DTDOccurence.ZeroOrMore:
  384. p.MinOccurs = 0;
  385. p.MaxOccursString = "unbounded";
  386. break;
  387. }
  388. return p;
  389. }
  390. XmlSchemaParticle CreateXsdParticleCore ()
  391. {
  392. XmlSchemaParticle p = null;
  393. if (ElementName != null) {
  394. XmlSchemaElement el = new XmlSchemaElement ();
  395. SetLineInfo (el);
  396. el.RefName = new XmlQualifiedName (ElementName);
  397. return el;
  398. }
  399. else if (ChildModels.Count == 0)
  400. return null;
  401. else {
  402. XmlSchemaGroupBase gb =
  403. (OrderType == DTDContentOrderType.Seq) ?
  404. (XmlSchemaGroupBase)
  405. new XmlSchemaSequence () :
  406. new XmlSchemaChoice ();
  407. SetLineInfo (gb);
  408. foreach (DTDContentModel cm in ChildModels.Items) {
  409. XmlSchemaParticle c = cm.CreateXsdParticle ();
  410. if (c != null)
  411. gb.Items.Add (c);
  412. }
  413. p = gb;
  414. }
  415. return p;
  416. }
  417. private DTDAutomata CompileInternal ()
  418. {
  419. if (ElementDecl.IsAny)
  420. return root.Any;
  421. if (ElementDecl.IsEmpty)
  422. return root.Empty;
  423. DTDAutomata basis = GetBasicContentAutomata ();
  424. switch (Occurence) {
  425. case DTDOccurence.One:
  426. return basis;
  427. case DTDOccurence.Optional:
  428. return Choice (root.Empty, basis);
  429. case DTDOccurence.OneOrMore:
  430. return new DTDOneOrMoreAutomata (root, basis);
  431. case DTDOccurence.ZeroOrMore:
  432. return Choice (root.Empty, new DTDOneOrMoreAutomata (root, basis));
  433. }
  434. throw new InvalidOperationException ();
  435. }
  436. private DTDAutomata GetBasicContentAutomata ()
  437. {
  438. if (ElementName != null)
  439. return new DTDElementAutomata (root, ElementName);
  440. switch (ChildModels.Count) {
  441. case 0:
  442. return root.Empty;
  443. case 1:
  444. return ChildModels [0].GetAutomata ();
  445. }
  446. DTDAutomata current = null;
  447. int childCount = ChildModels.Count;
  448. switch (OrderType) {
  449. case DTDContentOrderType.Seq:
  450. current = Sequence (
  451. ChildModels [childCount - 2].GetAutomata (),
  452. ChildModels [childCount - 1].GetAutomata ());
  453. for (int i = childCount - 2; i > 0; i--)
  454. current = Sequence (
  455. ChildModels [i - 1].GetAutomata (), current);
  456. return current;
  457. case DTDContentOrderType.Or:
  458. current = Choice (
  459. ChildModels [childCount - 2].GetAutomata (),
  460. ChildModels [childCount - 1].GetAutomata ());
  461. for (int i = childCount - 2; i > 0; i--)
  462. current = Choice (
  463. ChildModels [i - 1].GetAutomata (), current);
  464. return current;
  465. default:
  466. throw new InvalidOperationException ("Invalid pattern specification");
  467. }
  468. }
  469. private DTDAutomata Sequence (DTDAutomata l, DTDAutomata r)
  470. {
  471. return root.Factory.Sequence (l, r);
  472. }
  473. private DTDAutomata Choice (DTDAutomata l, DTDAutomata r)
  474. {
  475. return l.MakeChoice (r);
  476. }
  477. }
  478. internal class DTDContentModelCollection
  479. {
  480. ArrayList contentModel = new ArrayList ();
  481. public DTDContentModelCollection ()
  482. {
  483. }
  484. public IList Items {
  485. get { return contentModel; }
  486. }
  487. public DTDContentModel this [int i] {
  488. get { return contentModel [i] as DTDContentModel; }
  489. }
  490. public int Count {
  491. get { return contentModel.Count; }
  492. }
  493. public void Add (DTDContentModel model)
  494. {
  495. contentModel.Add (model);
  496. }
  497. }
  498. internal abstract class DTDNode : IXmlLineInfo
  499. {
  500. DTDObjectModel root;
  501. bool isInternalSubset;
  502. string baseURI;
  503. int lineNumber;
  504. int linePosition;
  505. public virtual string BaseURI {
  506. get { return baseURI; }
  507. set { baseURI = value; }
  508. }
  509. public bool IsInternalSubset {
  510. get { return isInternalSubset; }
  511. set { isInternalSubset = value; }
  512. }
  513. public int LineNumber {
  514. get { return lineNumber; }
  515. set { lineNumber = value; }
  516. }
  517. public int LinePosition {
  518. get { return linePosition; }
  519. set { linePosition = value; }
  520. }
  521. public bool HasLineInfo ()
  522. {
  523. return lineNumber != 0;
  524. }
  525. internal void SetRoot (DTDObjectModel root)
  526. {
  527. this.root = root;
  528. if (baseURI == null)
  529. this.BaseURI = root.BaseURI;
  530. }
  531. protected DTDObjectModel Root {
  532. get { return root; }
  533. }
  534. internal XmlException NotWFError (string message)
  535. {
  536. return new XmlException (this as IXmlLineInfo, BaseURI, message);
  537. }
  538. public void SetLineInfo (XmlSchemaObject obj)
  539. {
  540. obj.SourceUri = BaseURI;
  541. obj.LineNumber = LineNumber;
  542. obj.LinePosition = LinePosition;
  543. }
  544. }
  545. internal class DTDElementDeclaration : DTDNode
  546. {
  547. DTDObjectModel root;
  548. DTDContentModel contentModel;
  549. string name;
  550. bool isEmpty;
  551. bool isAny;
  552. bool isMixedContent;
  553. internal DTDElementDeclaration (DTDObjectModel root)
  554. {
  555. this.root = root;
  556. }
  557. public string Name {
  558. get { return name; }
  559. set { name = value; }
  560. }
  561. public bool IsEmpty {
  562. get { return isEmpty; }
  563. set { isEmpty = value; }
  564. }
  565. public bool IsAny {
  566. get { return isAny; }
  567. set { isAny = value; }
  568. }
  569. public bool IsMixedContent {
  570. get { return isMixedContent; }
  571. set { isMixedContent = value; }
  572. }
  573. public DTDContentModel ContentModel {
  574. get {
  575. if (contentModel == null)
  576. contentModel = new DTDContentModel (root, Name);
  577. return contentModel;
  578. }
  579. }
  580. public DTDAttListDeclaration Attributes {
  581. get {
  582. return Root.AttListDecls [Name];
  583. }
  584. }
  585. internal XmlSchemaElement CreateXsdElement ()
  586. {
  587. XmlSchemaElement el = new XmlSchemaElement ();
  588. SetLineInfo (el);
  589. el.Name = Name;
  590. XmlSchemaComplexType ct = new XmlSchemaComplexType ();
  591. el.SchemaType = ct;
  592. if (Attributes != null) {
  593. SetLineInfo (ct);
  594. foreach (DTDAttributeDefinition a in
  595. Attributes.Definitions)
  596. ct.Attributes.Add (a.CreateXsdAttribute ());
  597. }
  598. if (IsEmpty)
  599. ; // nothing to do
  600. else if (IsAny) {
  601. XmlSchemaAny any = new XmlSchemaAny ();
  602. any.MinOccurs = 0;
  603. any.MaxOccursString = "unbounded";
  604. ct.Particle = any;
  605. }
  606. else {
  607. if (IsMixedContent)
  608. ct.IsMixed = true;
  609. ct.Particle = ContentModel.CreateXsdParticle ();
  610. }
  611. /*
  612. if (IsEmpty) {
  613. el.SchemaType = new XmlSchemaComplexType ();
  614. SetLineInfo (el.SchemaType);
  615. }
  616. else if (IsAny)
  617. el.SchemaTypeName = new XmlQualifiedName (
  618. "anyType", XmlSchema.Namespace);
  619. else {
  620. XmlSchemaComplexType ct = new XmlSchemaComplexType ();
  621. SetLineInfo (ct);
  622. if (Attributes != null)
  623. foreach (DTDAttributeDefinition a in
  624. Attributes.Definitions)
  625. ct.Attributes.Add (a.CreateXsdAttribute ());
  626. if (IsMixedContent)
  627. ct.IsMixed = true;
  628. ct.Particle = ContentModel.CreateXsdParticle ();
  629. el.SchemaType = ct;
  630. }
  631. */
  632. return el;
  633. }
  634. }
  635. internal class DTDAttributeDefinition : DTDNode
  636. {
  637. string name;
  638. XmlSchemaDatatype datatype;
  639. ArrayList enumeratedLiterals;
  640. string unresolvedDefault;
  641. ArrayList enumeratedNotations;
  642. DTDAttributeOccurenceType occurenceType = DTDAttributeOccurenceType.None;
  643. string resolvedDefaultValue;
  644. string resolvedNormalizedDefaultValue;
  645. internal DTDAttributeDefinition (DTDObjectModel root)
  646. {
  647. this.SetRoot (root);
  648. }
  649. public string Name {
  650. get { return name; }
  651. set { name =value; }
  652. }
  653. public XmlSchemaDatatype Datatype {
  654. get { return datatype; }
  655. set { datatype = value; }
  656. }
  657. public DTDAttributeOccurenceType OccurenceType {
  658. get { return this.occurenceType; }
  659. set { this.occurenceType = value; }
  660. }
  661. // entity reference inside enumerated values are not allowed,
  662. // but on the other hand, they are allowed inside default value.
  663. // Then I decided to use string ArrayList for enumerated values,
  664. // and unresolved string value for DefaultValue.
  665. public ArrayList EnumeratedAttributeDeclaration {
  666. get {
  667. if (enumeratedLiterals == null)
  668. enumeratedLiterals = new ArrayList ();
  669. return this.enumeratedLiterals;
  670. }
  671. }
  672. public ArrayList EnumeratedNotations {
  673. get {
  674. if (enumeratedNotations == null)
  675. enumeratedNotations = new ArrayList ();
  676. return this.enumeratedNotations;
  677. }
  678. }
  679. public string DefaultValue {
  680. get {
  681. if (resolvedDefaultValue == null)
  682. resolvedDefaultValue = ComputeDefaultValue ();
  683. return resolvedDefaultValue;
  684. }
  685. }
  686. public string NormalizedDefaultValue {
  687. get {
  688. if (resolvedNormalizedDefaultValue == null) {
  689. string s = ComputeDefaultValue ();
  690. try {
  691. object o = Datatype.ParseValue (s, null, null);
  692. resolvedNormalizedDefaultValue =
  693. (o is string []) ?
  694. String.Join (" ", (string []) o) :
  695. o is IFormattable ? ((IFormattable) o).ToString (null, CultureInfo.InvariantCulture) : o.ToString ();
  696. } catch (Exception) {
  697. // This is for non-error-reporting reader
  698. resolvedNormalizedDefaultValue = Datatype.Normalize (s);
  699. }
  700. }
  701. return resolvedNormalizedDefaultValue;
  702. }
  703. }
  704. public string UnresolvedDefaultValue {
  705. get { return this.unresolvedDefault; }
  706. set { this.unresolvedDefault = value; }
  707. }
  708. public char QuoteChar {
  709. get {
  710. return UnresolvedDefaultValue.Length > 0 ?
  711. this.UnresolvedDefaultValue [0] :
  712. '"';
  713. }
  714. }
  715. internal XmlSchemaAttribute CreateXsdAttribute ()
  716. {
  717. XmlSchemaAttribute a = new XmlSchemaAttribute ();
  718. SetLineInfo (a);
  719. a.Name = Name;
  720. a.DefaultValue = resolvedNormalizedDefaultValue;
  721. XmlQualifiedName qname = XmlQualifiedName.Empty;
  722. ArrayList enumeration = null;
  723. if (enumeratedNotations != null && enumeratedNotations.Count > 0) {
  724. qname = new XmlQualifiedName ("NOTATION", XmlSchema.Namespace);
  725. enumeration = enumeratedNotations;
  726. }
  727. else if (enumeratedLiterals != null)
  728. enumeration = enumeratedLiterals;
  729. else {
  730. switch (Datatype.TokenizedType) {
  731. case XmlTokenizedType.ID:
  732. qname = new XmlQualifiedName ("ID", XmlSchema.Namespace); break;
  733. case XmlTokenizedType.IDREF:
  734. qname = new XmlQualifiedName ("IDREF", XmlSchema.Namespace); break;
  735. case XmlTokenizedType.IDREFS:
  736. qname = new XmlQualifiedName ("IDREFS", XmlSchema.Namespace); break;
  737. case XmlTokenizedType.ENTITY:
  738. qname = new XmlQualifiedName ("ENTITY", XmlSchema.Namespace); break;
  739. case XmlTokenizedType.ENTITIES:
  740. qname = new XmlQualifiedName ("ENTITIES", XmlSchema.Namespace); break;
  741. case XmlTokenizedType.NMTOKEN:
  742. qname = new XmlQualifiedName ("NMTOKEN", XmlSchema.Namespace); break;
  743. case XmlTokenizedType.NMTOKENS:
  744. qname = new XmlQualifiedName ("NMTOKENS", XmlSchema.Namespace); break;
  745. case XmlTokenizedType.NOTATION:
  746. qname = new XmlQualifiedName ("NOTATION", XmlSchema.Namespace); break;
  747. }
  748. }
  749. if (enumeration != null) {
  750. XmlSchemaSimpleType st = new XmlSchemaSimpleType ();
  751. SetLineInfo (st);
  752. XmlSchemaSimpleTypeRestriction r =
  753. new XmlSchemaSimpleTypeRestriction ();
  754. SetLineInfo (r);
  755. r.BaseTypeName = qname;
  756. if (enumeratedNotations != null) {
  757. foreach (string name in enumeratedNotations) {
  758. XmlSchemaEnumerationFacet f =
  759. new XmlSchemaEnumerationFacet ();
  760. SetLineInfo (f);
  761. r.Facets.Add (f);
  762. f.Value = name;
  763. }
  764. }
  765. st.Content = r;
  766. }
  767. else if (qname != XmlQualifiedName.Empty)
  768. a.SchemaTypeName = qname;
  769. return a;
  770. }
  771. internal string ComputeDefaultValue ()
  772. {
  773. if (UnresolvedDefaultValue == null)
  774. return null;
  775. StringBuilder sb = new StringBuilder ();
  776. int pos = 0;
  777. int next = 0;
  778. string value = this.UnresolvedDefaultValue;
  779. while ((next = value.IndexOf ('&', pos)) >= 0) {
  780. int semicolon = value.IndexOf (';', next);
  781. if (value [next + 1] == '#') {
  782. // character reference.
  783. char c = value [next + 2];
  784. NumberStyles style = NumberStyles.Integer;
  785. string spec;
  786. if (c == 'x' || c == 'X') {
  787. spec = value.Substring (next + 3, semicolon - next - 3);
  788. style |= NumberStyles.HexNumber;
  789. }
  790. else
  791. spec = value.Substring (next + 2, semicolon - next - 2);
  792. sb.Append ((char) int.Parse (spec, style, CultureInfo.InvariantCulture));
  793. } else {
  794. sb.Append (value.Substring (pos, next - 1));
  795. string name = value.Substring (next + 1, semicolon - 2);
  796. int predefined = XmlChar.GetPredefinedEntity (name);
  797. if (predefined >= 0)
  798. sb.Append (predefined);
  799. else
  800. sb.Append (Root.ResolveEntity (name));
  801. }
  802. pos = semicolon + 1;
  803. }
  804. sb.Append (value.Substring (pos));
  805. // strip quote chars
  806. string ret = sb.ToString (1, sb.Length - 2);
  807. sb.Length = 0;
  808. return ret;
  809. }
  810. }
  811. internal class DTDAttListDeclaration : DTDNode
  812. {
  813. string name;
  814. Hashtable attributeOrders = new Hashtable ();
  815. ArrayList attributes = new ArrayList ();
  816. internal DTDAttListDeclaration (DTDObjectModel root)
  817. {
  818. SetRoot (root);
  819. }
  820. public string Name {
  821. get { return name; }
  822. set { name = value; }
  823. }
  824. public DTDAttributeDefinition this [int i] {
  825. get { return Get (i); }
  826. }
  827. public DTDAttributeDefinition this [string name] {
  828. get { return Get (name); }
  829. }
  830. public DTDAttributeDefinition Get (int i)
  831. {
  832. return attributes [i] as DTDAttributeDefinition;
  833. }
  834. public DTDAttributeDefinition Get (string name)
  835. {
  836. object o = attributeOrders [name];
  837. if (o != null)
  838. return attributes [(int) o] as DTDAttributeDefinition;
  839. else
  840. return null;
  841. }
  842. public IList Definitions {
  843. get { return attributes; }
  844. }
  845. public void Add (DTDAttributeDefinition def)
  846. {
  847. if (attributeOrders [def.Name] != null)
  848. throw new InvalidOperationException (String.Format (
  849. "Attribute definition for {0} was already added at element {1}.",
  850. def.Name, this.Name));
  851. def.SetRoot (Root);
  852. attributeOrders.Add (def.Name, attributes.Count);
  853. attributes.Add (def);
  854. }
  855. public int Count {
  856. get { return attributeOrders.Count; }
  857. }
  858. }
  859. internal class DTDEntityBase : DTDNode
  860. {
  861. string name;
  862. string publicId;
  863. string systemId;
  864. string literalValue;
  865. string replacementText;
  866. string uriString;
  867. Uri absUri;
  868. bool isInvalid;
  869. // Exception loadException;
  870. bool loadFailed;
  871. XmlResolver resolver;
  872. protected DTDEntityBase (DTDObjectModel root)
  873. {
  874. SetRoot (root);
  875. }
  876. internal bool IsInvalid {
  877. get { return isInvalid; }
  878. set { isInvalid = value; }
  879. }
  880. public bool LoadFailed {
  881. get { return loadFailed; }
  882. set { loadFailed = value; }
  883. }
  884. public string Name {
  885. get { return name; }
  886. set { name = value; }
  887. }
  888. public string PublicId {
  889. get { return publicId; }
  890. set { publicId = value; }
  891. }
  892. public string SystemId {
  893. get { return systemId; }
  894. set { systemId = value; }
  895. }
  896. public string LiteralEntityValue {
  897. get { return literalValue; }
  898. set { literalValue = value; }
  899. }
  900. public string ReplacementText {
  901. get { return replacementText; }
  902. set { replacementText = value; }
  903. }
  904. public XmlResolver XmlResolver {
  905. set { resolver = value; }
  906. }
  907. public string ActualUri {
  908. get {
  909. if (uriString == null) {
  910. if (resolver == null || SystemId == null || SystemId.Length == 0)
  911. uriString = BaseURI;
  912. else {
  913. Uri baseUri = null;
  914. try {
  915. if (BaseURI != null && BaseURI.Length > 0)
  916. baseUri = new Uri (BaseURI);
  917. } catch (UriFormatException) {
  918. }
  919. absUri = resolver.ResolveUri (baseUri, SystemId);
  920. uriString = absUri != null ? absUri.ToString () : String.Empty;
  921. }
  922. }
  923. return uriString;
  924. }
  925. }
  926. public void Resolve ()
  927. {
  928. if (ActualUri == String.Empty) {
  929. LoadFailed = true;
  930. LiteralEntityValue = String.Empty;
  931. return;
  932. }
  933. if (Root.ExternalResources.ContainsKey (ActualUri))
  934. LiteralEntityValue = (string) Root.ExternalResources [ActualUri];
  935. Stream s = null;
  936. try {
  937. s = resolver.GetEntity (absUri, null, typeof (Stream)) as Stream;
  938. XmlTextReaderImpl xtr = new XmlTextReaderImpl (ActualUri, s, Root.NameTable);
  939. // Don't skip Text declaration here. LiteralEntityValue contains it. See spec 4.5
  940. LiteralEntityValue = xtr.GetRemainder ().ReadToEnd ();
  941. Root.ExternalResources.Add (ActualUri, LiteralEntityValue);
  942. if (Root.ExternalResources.Count > DTDObjectModel.AllowedExternalEntitiesMax)
  943. throw new InvalidOperationException ("The total amount of external entities exceeded the allowed number.");
  944. } catch (Exception ex) {
  945. // loadException = ex;
  946. LiteralEntityValue = String.Empty;
  947. LoadFailed = true;
  948. // throw NotWFError ("Cannot resolve external entity. URI is " + ActualUri + " .");
  949. } finally {
  950. if (s != null)
  951. s.Close ();
  952. }
  953. }
  954. }
  955. internal class DTDEntityDeclaration : DTDEntityBase
  956. {
  957. string entityValue;
  958. string notationName;
  959. ArrayList ReferencingEntities = new ArrayList ();
  960. bool scanned;
  961. bool recursed;
  962. bool hasExternalReference;
  963. internal DTDEntityDeclaration (DTDObjectModel root) : base (root)
  964. {
  965. }
  966. public string NotationName {
  967. get { return notationName; }
  968. set { notationName = value; }
  969. }
  970. public bool HasExternalReference {
  971. get {
  972. if (!scanned)
  973. ScanEntityValue (new ArrayList ());
  974. return hasExternalReference;
  975. }
  976. }
  977. public string EntityValue {
  978. get {
  979. if (this.IsInvalid)
  980. return String.Empty;
  981. if (PublicId == null && SystemId == null && LiteralEntityValue == null)
  982. return String.Empty;
  983. if (entityValue == null) {
  984. if (NotationName != null)
  985. entityValue = "";
  986. else if (SystemId == null || SystemId == String.Empty) {
  987. entityValue = ReplacementText;
  988. if (entityValue == null)
  989. entityValue = String.Empty;
  990. } else {
  991. entityValue = ReplacementText;
  992. }
  993. // Check illegal recursion.
  994. ScanEntityValue (new ArrayList ());
  995. }
  996. return entityValue;
  997. }
  998. }
  999. // It returns whether the entity contains references to external entities.
  1000. public void ScanEntityValue (ArrayList refs)
  1001. {
  1002. // To modify this code, beware nesting between this and EntityValue.
  1003. string value = EntityValue;
  1004. if (this.SystemId != null)
  1005. hasExternalReference = true;
  1006. if (recursed)
  1007. throw NotWFError ("Entity recursion was found.");
  1008. recursed = true;
  1009. if (scanned) {
  1010. foreach (string referenced in refs)
  1011. if (this.ReferencingEntities.Contains (referenced))
  1012. throw NotWFError (String.Format (
  1013. "Nested entity was found between {0} and {1}",
  1014. referenced, Name));
  1015. recursed = false;
  1016. return;
  1017. }
  1018. int len = value.Length;
  1019. int start = 0;
  1020. for (int i=0; i<len; i++) {
  1021. switch (value [i]) {
  1022. case '&':
  1023. start = i+1;
  1024. break;
  1025. case ';':
  1026. if (start == 0)
  1027. break;
  1028. string name = value.Substring (start, i - start);
  1029. if (name.Length == 0)
  1030. throw NotWFError ("Entity reference name is missing.");
  1031. if (name [0] == '#')
  1032. break; // character reference
  1033. if (XmlChar.GetPredefinedEntity (name) >= 0)
  1034. break; // predefined reference
  1035. this.ReferencingEntities.Add (name);
  1036. DTDEntityDeclaration decl = Root.EntityDecls [name];
  1037. if (decl != null) {
  1038. if (decl.SystemId != null)
  1039. hasExternalReference = true;
  1040. refs.Add (Name);
  1041. decl.ScanEntityValue (refs);
  1042. foreach (string str in decl.ReferencingEntities)
  1043. ReferencingEntities.Add (str);
  1044. refs.Remove (Name);
  1045. value = value.Remove (start - 1, name.Length + 2);
  1046. value = value.Insert (start - 1, decl.EntityValue);
  1047. i -= name.Length + 1; // not +2, because of immediate i++ .
  1048. len = value.Length;
  1049. }
  1050. start = 0;
  1051. break;
  1052. }
  1053. }
  1054. if (start != 0)
  1055. Root.AddError (new XmlSchemaException ("Invalid reference character '&' is specified.",
  1056. this.LineNumber, this.LinePosition, null, this.BaseURI, null));
  1057. scanned = true;
  1058. recursed = false;
  1059. }
  1060. }
  1061. internal class DTDNotationDeclaration : DTDNode
  1062. {
  1063. string name;
  1064. string localName;
  1065. string prefix;
  1066. string publicId;
  1067. string systemId;
  1068. public string Name {
  1069. get { return name; }
  1070. set { name = value; }
  1071. }
  1072. public string PublicId {
  1073. get { return publicId; }
  1074. set { publicId = value; }
  1075. }
  1076. public string SystemId {
  1077. get { return systemId; }
  1078. set { systemId = value; }
  1079. }
  1080. public string LocalName {
  1081. get { return localName; }
  1082. set { localName = value; }
  1083. }
  1084. public string Prefix {
  1085. get { return prefix; }
  1086. set { prefix = value; }
  1087. }
  1088. internal DTDNotationDeclaration (DTDObjectModel root)
  1089. {
  1090. SetRoot (root);
  1091. }
  1092. }
  1093. internal class DTDParameterEntityDeclarationCollection
  1094. {
  1095. Hashtable peDecls = new Hashtable ();
  1096. DTDObjectModel root;
  1097. public DTDParameterEntityDeclarationCollection (DTDObjectModel root)
  1098. {
  1099. this.root = root;
  1100. }
  1101. public DTDParameterEntityDeclaration this [string name] {
  1102. get { return peDecls [name] as DTDParameterEntityDeclaration; }
  1103. }
  1104. public void Add (string name, DTDParameterEntityDeclaration decl)
  1105. {
  1106. // PEDecl can be overriden.
  1107. if (peDecls [name] != null)
  1108. return;
  1109. decl.SetRoot (root);
  1110. peDecls.Add (name, decl);
  1111. }
  1112. public ICollection Keys {
  1113. get { return peDecls.Keys; }
  1114. }
  1115. public ICollection Values {
  1116. get { return peDecls.Values; }
  1117. }
  1118. }
  1119. internal class DTDParameterEntityDeclaration : DTDEntityBase
  1120. {
  1121. internal DTDParameterEntityDeclaration (DTDObjectModel root) : base (root)
  1122. {
  1123. }
  1124. }
  1125. internal enum DTDContentOrderType
  1126. {
  1127. None,
  1128. Seq,
  1129. Or
  1130. }
  1131. internal enum DTDAttributeOccurenceType
  1132. {
  1133. None,
  1134. Required,
  1135. Optional,
  1136. Fixed
  1137. }
  1138. internal enum DTDOccurence
  1139. {
  1140. One,
  1141. Optional,
  1142. ZeroOrMore,
  1143. OneOrMore
  1144. }
  1145. }