XmlTextReader.cs 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680
  1. //
  2. // System.Xml.XmlTextReader
  3. //
  4. // Author:
  5. // Jason Diamond ([email protected])
  6. // Adam Treat ([email protected])
  7. // Atsushi Enomoto ([email protected])
  8. //
  9. // (C) 2001, 2002 Jason Diamond http://injektilo.org/
  10. //
  11. // FIXME:
  12. //
  13. // I haven't checked whether DTD parser runs correct.
  14. //
  15. // More strict well-formedness checking should be done.
  16. //
  17. // NameTables aren't being used completely yet.
  18. //
  19. // Some thought needs to be given to performance. There's too many
  20. // strings being allocated.
  21. //
  22. // Some of the MoveTo methods haven't been implemented yet.
  23. //
  24. // xml:space, xml:lang aren't being tracked.
  25. //
  26. using System;
  27. using System.Collections;
  28. using System.IO;
  29. using System.Text;
  30. using Mono.Xml;
  31. using Mono.Xml.Native;
  32. namespace System.Xml
  33. {
  34. public class XmlTextReader : XmlReader, IXmlLineInfo
  35. {
  36. WhitespaceHandling whitespaceHandling = WhitespaceHandling.All;
  37. #region Constructors
  38. protected XmlTextReader ()
  39. {
  40. }
  41. public XmlTextReader (Stream input)
  42. : this (new XmlStreamReader (input))
  43. {
  44. }
  45. public XmlTextReader (string url)
  46. : this(url, new NameTable ())
  47. {
  48. }
  49. public XmlTextReader (TextReader input)
  50. : this (input, new NameTable ())
  51. {
  52. }
  53. protected XmlTextReader (XmlNameTable nt)
  54. : this (String.Empty, null, XmlNodeType.None, null)
  55. {
  56. }
  57. public XmlTextReader (Stream input, XmlNameTable nt)
  58. : this(new XmlStreamReader (input), nt)
  59. {
  60. }
  61. public XmlTextReader (string url, Stream input)
  62. : this (url, new XmlStreamReader (input))
  63. {
  64. }
  65. public XmlTextReader (string url, TextReader input)
  66. : this (url, input, new NameTable ())
  67. {
  68. }
  69. [MonoTODO("Non-filename-url must be supported. Waiting for WebClient")]
  70. public XmlTextReader (string url, XmlNameTable nt)
  71. : this (url, new XmlStreamReader (url), nt)
  72. {
  73. }
  74. public XmlTextReader (TextReader input, XmlNameTable nt)
  75. : this (String.Empty, input, nt)
  76. {
  77. }
  78. public XmlTextReader (Stream xmlFragment, XmlNodeType fragType, XmlParserContext context)
  79. : this (context.BaseURI, new XmlStreamReader (xmlFragment), fragType, context)
  80. {
  81. }
  82. public XmlTextReader (string url, Stream input, XmlNameTable nt)
  83. : this (url, new XmlStreamReader (input), nt)
  84. {
  85. }
  86. public XmlTextReader (string url, TextReader input, XmlNameTable nt)
  87. : this (url, input, XmlNodeType.Document, null)
  88. {
  89. }
  90. [MonoTODO("TODO as same as private XmlTextReader(TextReader, XmlNodeType, XmlParserContext)")]
  91. public XmlTextReader (string xmlFragment, XmlNodeType fragType, XmlParserContext context)
  92. : this (context != null ? context.BaseURI : String.Empty,
  93. new StringReader (xmlFragment),
  94. fragType,
  95. context)
  96. {
  97. }
  98. // TODO still remains as described at head of this file,
  99. // but it might not be TODO of the constructors...
  100. XmlTextReader (string url, TextReader fragment, XmlNodeType fragType, XmlParserContext context)
  101. {
  102. this.Initialize (url, context, fragment, fragType);
  103. }
  104. #endregion
  105. #region Properties
  106. public override int AttributeCount
  107. {
  108. get { return attributes.Count; }
  109. }
  110. public override string BaseURI
  111. {
  112. get { return parserContext.BaseURI; }
  113. }
  114. public override int Depth
  115. {
  116. get {
  117. return elementDepth;
  118. }
  119. }
  120. public Encoding Encoding
  121. {
  122. get { return parserContext.Encoding; }
  123. }
  124. public override bool EOF
  125. {
  126. get
  127. {
  128. return
  129. readState == ReadState.EndOfFile ||
  130. readState == ReadState.Closed;
  131. }
  132. }
  133. public override bool HasValue
  134. {
  135. get { return value != String.Empty; }
  136. }
  137. public override bool IsDefault
  138. {
  139. get
  140. {
  141. // XmlTextReader does not expand default attributes.
  142. return false;
  143. }
  144. }
  145. public override bool IsEmptyElement
  146. {
  147. get { return isEmptyElement; }
  148. }
  149. public override string this [int i]
  150. {
  151. get { return GetAttribute (i); }
  152. }
  153. public override string this [string name]
  154. {
  155. get { return GetAttribute (name); }
  156. }
  157. public override string this [string localName, string namespaceName]
  158. {
  159. get { return GetAttribute (localName, namespaceName); }
  160. }
  161. public int LineNumber
  162. {
  163. get { return currentInput.LineNumber; }
  164. }
  165. public int LinePosition
  166. {
  167. get { return currentInput.LinePosition; }
  168. }
  169. public override string LocalName
  170. {
  171. get { return localName; }
  172. }
  173. public override string Name
  174. {
  175. get { return name; }
  176. }
  177. public bool Namespaces
  178. {
  179. get { return namespaces; }
  180. set {
  181. if (readState != ReadState.Initial)
  182. throw new InvalidOperationException ("Namespaces have to be set before reading.");
  183. namespaces = value;
  184. }
  185. }
  186. public override string NamespaceURI
  187. {
  188. get { return namespaceURI; }
  189. }
  190. public override XmlNameTable NameTable
  191. {
  192. get { return parserContext.NameTable; }
  193. }
  194. public override XmlNodeType NodeType
  195. {
  196. get { return nodeType; }
  197. }
  198. [MonoTODO]
  199. public bool Normalization
  200. {
  201. get { throw new NotImplementedException (); }
  202. set { throw new NotImplementedException (); }
  203. }
  204. public override string Prefix
  205. {
  206. get { return prefix; }
  207. }
  208. public override char QuoteChar
  209. {
  210. get {
  211. // value string holds attribute quotation char.
  212. if (NodeType == XmlNodeType.Attribute)
  213. return value [0];
  214. else
  215. return '"';
  216. }
  217. }
  218. public override ReadState ReadState
  219. {
  220. get { return readState; }
  221. }
  222. public override string Value
  223. {
  224. get {
  225. if(NodeType == XmlNodeType.Attribute)
  226. return UnescapeAttributeValue(value);
  227. else
  228. return value;
  229. }
  230. }
  231. public WhitespaceHandling WhitespaceHandling
  232. {
  233. get { return whitespaceHandling; }
  234. set { whitespaceHandling = value; }
  235. }
  236. [MonoTODO]
  237. public override string XmlLang
  238. {
  239. get { throw new NotImplementedException (); }
  240. }
  241. public XmlResolver XmlResolver
  242. {
  243. set { resolver = value; }
  244. }
  245. [MonoTODO]
  246. public override XmlSpace XmlSpace
  247. {
  248. get { throw new NotImplementedException (); }
  249. }
  250. #endregion
  251. #region Methods
  252. [MonoTODO]
  253. public override void Close ()
  254. {
  255. readState = ReadState.Closed;
  256. foreach (XmlParserInput input in parserInputStack.ToArray ())
  257. input.Close ();
  258. this.currentInput.Close ();
  259. }
  260. public override string GetAttribute (int i)
  261. {
  262. if (i > attributes.Count)
  263. throw new ArgumentOutOfRangeException ("i is smaller than AttributeCount");
  264. else
  265. return UnescapeAttributeValue (attributes [orderedAttributes [i]] as string);
  266. }
  267. public override string GetAttribute (string name)
  268. {
  269. return attributes.ContainsKey (name) ?
  270. UnescapeAttributeValue (attributes [name] as string) : String.Empty;
  271. }
  272. public override string GetAttribute (string localName, string namespaceURI)
  273. {
  274. foreach (DictionaryEntry entry in attributes)
  275. {
  276. string thisName = entry.Key as string;
  277. int indexOfColon = thisName.IndexOf (':');
  278. if (indexOfColon != -1) {
  279. string thisLocalName = thisName.Substring (indexOfColon + 1);
  280. if (localName == thisLocalName) {
  281. string thisPrefix = thisName.Substring (0, indexOfColon);
  282. string thisNamespaceURI = LookupNamespace (thisPrefix);
  283. if (namespaceURI == thisNamespaceURI)
  284. return attributes.ContainsKey (thisName) ?
  285. UnescapeAttributeValue (attributes [thisName] as string) : String.Empty;
  286. }
  287. } else if (localName == "xmlns" && namespaceURI == "http://www.w3.org/2000/xmlns/" && thisName == "xmlns")
  288. return attributes.ContainsKey (thisName) ?
  289. UnescapeAttributeValue (attributes [thisName] as string) : String.Empty;
  290. }
  291. return String.Empty;
  292. }
  293. [MonoTODO]
  294. public TextReader GetRemainder ()
  295. {
  296. throw new NotImplementedException ();
  297. }
  298. bool IXmlLineInfo.HasLineInfo ()
  299. {
  300. return true;
  301. }
  302. public override string LookupNamespace (string prefix)
  303. {
  304. return parserContext.NamespaceManager.LookupNamespace (prefix);
  305. }
  306. public override void MoveToAttribute (int i)
  307. {
  308. MoveToElement ();
  309. if (attributes == null || orderedAttributes.Count < i || i < 0)
  310. throw new ArgumentOutOfRangeException ("attribute index out of range.");
  311. string name = orderedAttributes [i] as string;
  312. string value = attributes [name] as string;
  313. SetProperties (
  314. XmlNodeType.Attribute, // nodeType
  315. name, // name
  316. false, // isEmptyElement
  317. value, // value
  318. false // clearAttributes
  319. );
  320. attributeValuePos = 0;
  321. }
  322. public override bool MoveToAttribute (string name)
  323. {
  324. MoveToElement ();
  325. bool match = false;
  326. if (attributes == null)
  327. return false;
  328. if (orderedAttributesEnumerator == null) {
  329. SaveProperties ();
  330. orderedAttributesEnumerator = orderedAttributes.GetEnumerator ();
  331. }
  332. while (orderedAttributesEnumerator.MoveNext ()) {
  333. if(name == orderedAttributesEnumerator.Current as string) {
  334. match = true;
  335. break;
  336. }
  337. }
  338. if (match) {
  339. string value = attributes [name] as string;
  340. SetProperties (
  341. XmlNodeType.Attribute, // nodeType
  342. name, // name
  343. false, // isEmptyElement
  344. value, // value
  345. false // clearAttributes
  346. );
  347. attributeValuePos = 0;
  348. }
  349. return match;
  350. }
  351. [MonoTODO]
  352. public override bool MoveToAttribute (string localName, string namespaceName)
  353. {
  354. throw new NotImplementedException ();
  355. }
  356. public override bool MoveToElement ()
  357. {
  358. if (orderedAttributesEnumerator != null) {
  359. orderedAttributesEnumerator = null;
  360. RestoreProperties ();
  361. return true;
  362. }
  363. return false;
  364. }
  365. public override bool MoveToFirstAttribute ()
  366. {
  367. MoveToElement ();
  368. return MoveToNextAttribute ();
  369. }
  370. public override bool MoveToNextAttribute ()
  371. {
  372. if (attributes == null)
  373. return false;
  374. if (orderedAttributesEnumerator == null) {
  375. SaveProperties ();
  376. orderedAttributesEnumerator = orderedAttributes.GetEnumerator ();
  377. }
  378. if (orderedAttributesEnumerator.MoveNext ()) {
  379. string name = orderedAttributesEnumerator.Current as string;
  380. string value = attributes [name] as string;
  381. SetProperties (
  382. XmlNodeType.Attribute, // nodeType
  383. name, // name
  384. false, // isEmptyElement
  385. value, // value
  386. false // clearAttributes
  387. );
  388. attributeValuePos = 0;
  389. return true;
  390. }
  391. return false;
  392. }
  393. public override bool Read ()
  394. {
  395. bool more = false;
  396. readState = ReadState.Interactive;
  397. more = ReadContent ();
  398. return more;
  399. }
  400. public override bool ReadAttributeValue ()
  401. {
  402. // 'attributeString' holds real string value (without their
  403. // quotation characters).
  404. //
  405. // 'attributeValuePos' holds current position
  406. // of 'attributeString' while iterating ReadAttribute().
  407. // It may be:
  408. // -1 if ReadAttributeValue() has already finished.
  409. // 0 if ReadAttributeValue() ready to start reading.
  410. // >0 if ReadAttributeValue() already got 1 or more values
  411. //
  412. // local 'refPosition' holds the position on the
  413. // attributeString which may be used next time.
  414. if (attributeValuePos < 0) {
  415. SetProperties (XmlNodeType.None,
  416. String.Empty,
  417. false,
  418. String.Empty,
  419. false);
  420. return false;
  421. }
  422. // If not started, then initialize attributeString when parsing is at start.
  423. if (attributeValuePos == 0)
  424. attributeString =
  425. value.Substring (1, value.Length - 2);
  426. returnEntityReference = false;
  427. value = String.Empty;
  428. int refPosition;
  429. int loop = 0;
  430. do {
  431. refPosition = attributeString.IndexOf ('&', attributeValuePos);
  432. if (refPosition < 0) {
  433. // Reached to the end of value string.
  434. value += attributeString.Substring (attributeValuePos);
  435. attributeValuePos = -1;
  436. break;
  437. } else if (refPosition == attributeValuePos) {
  438. string parsed = ReadAttributeValueReference ();
  439. if (parsed != null)
  440. value += parsed;
  441. else {
  442. // Found that an entity reference starts from this point.
  443. // reset position to after '&'.
  444. attributeValuePos = refPosition;
  445. if (value.Length <= 0) {
  446. int endNamePos = attributeString.IndexOf (";", attributeValuePos);
  447. value = attributeString.Substring (attributeValuePos+1, endNamePos - attributeValuePos - 1);
  448. attributeValuePos += value.Length + 2;
  449. returnEntityReference = true;
  450. }
  451. break;
  452. }
  453. } else {
  454. value += attributeString.Substring (attributeValuePos,
  455. refPosition - attributeValuePos);
  456. attributeValuePos = refPosition;
  457. continue;
  458. }
  459. } while (++loop > 0);
  460. if (returnEntityReference)
  461. SetProperties (XmlNodeType.EntityReference,
  462. value,
  463. false,
  464. String.Empty,
  465. false);
  466. else
  467. SetProperties (XmlNodeType.Text,
  468. "#text",
  469. false,
  470. value,
  471. false);
  472. return true;
  473. }
  474. [MonoTODO]
  475. public int ReadBase64 (byte [] buffer, int offset, int length)
  476. {
  477. throw new NotImplementedException ();
  478. }
  479. [MonoTODO]
  480. public int ReadBinHex (byte [] buffer, int offset, int length)
  481. {
  482. throw new NotImplementedException ();
  483. }
  484. [MonoTODO]
  485. public int ReadChars (char [] buffer, int offset, int length)
  486. {
  487. throw new NotImplementedException ();
  488. }
  489. public override string ReadInnerXml ()
  490. {
  491. if (readState != ReadState.Interactive)
  492. return String.Empty;
  493. switch (NodeType) {
  494. case XmlNodeType.Attribute:
  495. return value.Substring (1, value.Length - 2);
  496. case XmlNodeType.Element:
  497. if (IsEmptyElement)
  498. return String.Empty;
  499. int startDepth = depth;
  500. if (innerXmlBuilder == null)
  501. innerXmlBuilder = new StringBuilder ();
  502. innerXmlBuilder.Length = 0;
  503. do {
  504. // ReadContent ();
  505. Read ();
  506. if (NodeType != XmlNodeType.EndElement || depth + 1 > startDepth)
  507. innerXmlBuilder.Append (currentTag);
  508. } while (depth >= startDepth);
  509. string xml = innerXmlBuilder.ToString ();
  510. innerXmlBuilder.Length = 0;
  511. return xml;
  512. case XmlNodeType.None:
  513. // MS document is incorrect. Seems not to progress.
  514. return String.Empty;
  515. default:
  516. Read ();
  517. return String.Empty;
  518. }
  519. }
  520. public override string ReadOuterXml ()
  521. {
  522. if (readState != ReadState.Interactive)
  523. return String.Empty;
  524. switch (NodeType) {
  525. case XmlNodeType.Attribute:
  526. // strictly incompatible with MS... (it holds spaces attribute between name, value and "=" char (very trivial).
  527. return String.Format ("{0}={1}{2}{1}", Name, QuoteChar, ReadInnerXml ());
  528. case XmlNodeType.Element:
  529. bool isEmpty = IsEmptyElement;
  530. string startTag = currentTag.ToString ();
  531. string name = Name;
  532. if (NodeType == XmlNodeType.Element && !isEmpty)
  533. return String.Format ("{0}{1}</{2}>", startTag, ReadInnerXml (), name);
  534. else
  535. return currentTag.ToString ();
  536. case XmlNodeType.None:
  537. // MS document is incorrect. Seems not to progress.
  538. return String.Empty;
  539. default:
  540. Read ();
  541. return String.Empty;
  542. }
  543. }
  544. public override string ReadString ()
  545. {
  546. if (readStringBuffer == null)
  547. readStringBuffer = new StringBuilder ();
  548. readStringBuffer.Length = 0;
  549. switch (NodeType) {
  550. default:
  551. return String.Empty;
  552. case XmlNodeType.Element:
  553. if (IsEmptyElement)
  554. return String.Empty;
  555. do {
  556. Read ();
  557. switch (NodeType) {
  558. case XmlNodeType.Text:
  559. case XmlNodeType.CDATA:
  560. case XmlNodeType.Whitespace:
  561. case XmlNodeType.SignificantWhitespace:
  562. readStringBuffer.Append (Value);
  563. continue;
  564. }
  565. break;
  566. } while (true);
  567. break;
  568. case XmlNodeType.Text:
  569. case XmlNodeType.CDATA:
  570. case XmlNodeType.Whitespace:
  571. case XmlNodeType.SignificantWhitespace:
  572. do {
  573. switch (NodeType) {
  574. case XmlNodeType.Text:
  575. case XmlNodeType.CDATA:
  576. case XmlNodeType.Whitespace:
  577. case XmlNodeType.SignificantWhitespace:
  578. readStringBuffer.Append (Value);
  579. Read ();
  580. continue;
  581. }
  582. break;
  583. } while (true);
  584. break;
  585. }
  586. string ret = readStringBuffer.ToString ();
  587. readStringBuffer.Length = 0;
  588. return ret;
  589. }
  590. [MonoTODO]
  591. public void ResetState ()
  592. {
  593. throw new NotImplementedException ();
  594. }
  595. public override void ResolveEntity ()
  596. {
  597. // XmlTextReaders don't resolve entities.
  598. throw new InvalidOperationException ("XmlTextReader cannot resolve external entities.");
  599. }
  600. #endregion
  601. #region Internals
  602. // Parsed DTD Objects
  603. internal DTDObjectModel currentSubset;
  604. internal void Initialize (string url, XmlParserContext context, TextReader fragment, XmlNodeType fragType)
  605. {
  606. parserContext = context;
  607. if (context == null) {
  608. XmlNameTable nt = new NameTable ();
  609. parserContext = new XmlParserContext (nt,
  610. new XmlNamespaceManager (nt),
  611. String.Empty,
  612. XmlSpace.None);
  613. }
  614. if (url != null && url != String.Empty)
  615. parserContext.BaseURI = url;
  616. Init ();
  617. switch (fragType) {
  618. case XmlNodeType.Attribute:
  619. value = "''";
  620. break;
  621. case XmlNodeType.Element:
  622. allowMultipleRoot = true;
  623. break;
  624. case XmlNodeType.Document:
  625. break;
  626. default:
  627. throw new XmlException (String.Format ("NodeType {0} is not allowed to create XmlTextReader.", fragType));
  628. }
  629. this.currentInput = new XmlParserInput (fragment, url);
  630. StreamReader sr = fragment as StreamReader;
  631. }
  632. #endregion
  633. #region Privates
  634. private XmlParserContext parserContext;
  635. private XmlParserInput currentInput;
  636. private Stack parserInputStack = new Stack ();
  637. private ReadState readState;
  638. private int depth;
  639. private int elementDepth;
  640. private bool depthDown;
  641. private bool popScope;
  642. private Stack elementStack;
  643. private Stack baseURIStack;
  644. private bool haveEnteredDocument;
  645. private bool allowMultipleRoot = false;
  646. private XmlNodeType nodeType;
  647. private string name;
  648. private string prefix;
  649. private string localName;
  650. private string namespaceURI;
  651. private bool isEmptyElement;
  652. private string value;
  653. private XmlNodeType saveNodeType;
  654. private string saveName;
  655. private string savePrefix;
  656. private string saveLocalName;
  657. private string saveNamespaceURI;
  658. private bool saveIsEmptyElement;
  659. private Hashtable attributes;
  660. private ArrayList orderedAttributes;
  661. private IEnumerator orderedAttributesEnumerator;
  662. private bool returnEntityReference;
  663. private string entityReferenceName;
  664. private char [] nameBuffer;
  665. private int nameLength;
  666. private int nameCapacity;
  667. private const int initialNameCapacity = 256;
  668. private char [] valueBuffer;
  669. private int valueLength;
  670. private int valueCapacity;
  671. private const int initialValueCapacity = 8192;
  672. // A buffer for ReadContent for ReadOuterXml
  673. private StringBuilder currentTag {
  674. get {
  675. return currentInput.CurrentMarkup;
  676. }
  677. }
  678. private string attributeString = String.Empty;
  679. private int attributeValuePos;
  680. // This should be only referenced(used) by ReadInnerXml(). Kind of flyweight pattern.
  681. private StringBuilder innerXmlBuilder;
  682. private StringBuilder readStringBuffer;
  683. // Parameter entity placeholder
  684. private Hashtable parameterEntities = new Hashtable ();
  685. int dtdIncludeSect;
  686. private XmlResolver resolver = new XmlUrlResolver ();
  687. private bool namespaces = true;
  688. private XmlException ReaderError (string message)
  689. {
  690. return new XmlException (message, LineNumber, LinePosition);
  691. }
  692. private void Init ()
  693. {
  694. readState = ReadState.Initial;
  695. depth = 0;
  696. depthDown = false;
  697. popScope = false;
  698. elementStack = new Stack();
  699. baseURIStack = new Stack();
  700. haveEnteredDocument = false;
  701. nodeType = XmlNodeType.None;
  702. name = String.Empty;
  703. prefix = String.Empty;
  704. localName = string.Empty;
  705. isEmptyElement = false;
  706. value = String.Empty;
  707. attributes = new Hashtable ();
  708. orderedAttributes = new ArrayList ();
  709. orderedAttributesEnumerator = null;
  710. returnEntityReference = false;
  711. entityReferenceName = String.Empty;
  712. nameBuffer = new char [initialNameCapacity];
  713. nameLength = 0;
  714. nameCapacity = initialNameCapacity;
  715. valueBuffer = new char [initialValueCapacity];
  716. valueLength = 0;
  717. valueCapacity = initialValueCapacity;
  718. }
  719. // Use this method rather than setting the properties
  720. // directly so that all the necessary properties can
  721. // be changed in harmony with each other. Maybe the
  722. // fields should be in a seperate class to help enforce
  723. // this.
  724. private void SetProperties (
  725. XmlNodeType nodeType,
  726. string name,
  727. bool isEmptyElement,
  728. string value,
  729. bool clearAttributes)
  730. {
  731. this.nodeType = nodeType;
  732. this.name = name;
  733. this.isEmptyElement = isEmptyElement;
  734. this.value = value;
  735. this.elementDepth = depth;
  736. if (clearAttributes)
  737. ClearAttributes ();
  738. if (namespaces) {
  739. int indexOfColon = name.IndexOf (':');
  740. if (indexOfColon == -1) {
  741. prefix = String.Empty;
  742. localName = name;
  743. } else {
  744. prefix = name.Substring (0, indexOfColon);
  745. localName = name.Substring (indexOfColon + 1);
  746. }
  747. } else {
  748. prefix = String.Empty;
  749. localName = name;
  750. }
  751. namespaceURI = LookupNamespace (prefix);
  752. }
  753. private void SaveProperties ()
  754. {
  755. saveNodeType = nodeType;
  756. saveName = name;
  757. savePrefix = prefix;
  758. saveLocalName = localName;
  759. saveNamespaceURI = namespaceURI;
  760. saveIsEmptyElement = isEmptyElement;
  761. // An element's value is always String.Empty.
  762. }
  763. private void RestoreProperties ()
  764. {
  765. nodeType = saveNodeType;
  766. name = saveName;
  767. prefix = savePrefix;
  768. localName = saveLocalName;
  769. namespaceURI = saveNamespaceURI;
  770. isEmptyElement = saveIsEmptyElement;
  771. value = String.Empty;
  772. }
  773. private void AddAttribute (string name, string value)
  774. {
  775. attributes.Add (name, value);
  776. orderedAttributes.Add (name);
  777. }
  778. private void ClearAttributes ()
  779. {
  780. if (attributes.Count > 0) {
  781. attributes.Clear ();
  782. orderedAttributes.Clear ();
  783. }
  784. orderedAttributesEnumerator = null;
  785. }
  786. private int PeekChar ()
  787. {
  788. return currentInput.PeekChar ();
  789. }
  790. private int ReadChar ()
  791. {
  792. return currentInput.ReadChar ();
  793. }
  794. // This should really keep track of some state so
  795. // that it's not possible to have more than one document
  796. // element or text outside of the document element.
  797. private bool ReadContent ()
  798. {
  799. currentTag.Length = 0;
  800. if (popScope) {
  801. parserContext.NamespaceManager.PopScope ();
  802. popScope = false;
  803. }
  804. if (returnEntityReference) {
  805. SetEntityReferenceProperties ();
  806. } else {
  807. switch (PeekChar ()) {
  808. case '<':
  809. ReadChar ();
  810. ReadTag ();
  811. break;
  812. case '\r': goto case ' ';
  813. case '\n': goto case ' ';
  814. case '\t': goto case ' ';
  815. case ' ':
  816. if (whitespaceHandling == WhitespaceHandling.All ||
  817. whitespaceHandling == WhitespaceHandling.Significant)
  818. return ReadWhitespace ();
  819. SkipWhitespace ();
  820. return ReadContent ();
  821. case -1:
  822. if (depth > 0)
  823. throw new XmlException ("unexpected end of file. Current depth is " + depth);
  824. readState = ReadState.EndOfFile;
  825. SetProperties (
  826. XmlNodeType.None, // nodeType
  827. String.Empty, // name
  828. false, // isEmptyElement
  829. String.Empty, // value
  830. true // clearAttributes
  831. );
  832. break;
  833. default:
  834. ReadText (true);
  835. break;
  836. }
  837. }
  838. return this.ReadState != ReadState.EndOfFile;
  839. }
  840. private void SetEntityReferenceProperties ()
  841. {
  842. SetProperties (
  843. XmlNodeType.EntityReference, // nodeType
  844. entityReferenceName, // name
  845. false, // isEmptyElement
  846. String.Empty, // value
  847. true // clearAttributes
  848. );
  849. returnEntityReference = false;
  850. entityReferenceName = String.Empty;
  851. }
  852. // The leading '<' has already been consumed.
  853. private void ReadTag ()
  854. {
  855. switch (PeekChar ())
  856. {
  857. case '/':
  858. ReadChar ();
  859. ReadEndTag ();
  860. break;
  861. case '?':
  862. ReadChar ();
  863. ReadProcessingInstruction ();
  864. break;
  865. case '!':
  866. ReadChar ();
  867. ReadDeclaration ();
  868. break;
  869. default:
  870. ReadStartTag ();
  871. break;
  872. }
  873. }
  874. // The leading '<' has already been consumed.
  875. private void ReadStartTag ()
  876. {
  877. parserContext.NamespaceManager.PushScope ();
  878. string name = ReadName ();
  879. if (haveEnteredDocument && elementStack.Count == 0 && !allowMultipleRoot)
  880. throw ReaderError("document has terminated, cannot open new element");
  881. haveEnteredDocument = true;
  882. SkipWhitespace ();
  883. bool isEmptyElement = false;
  884. ClearAttributes ();
  885. if (XmlConstructs.IsNameStart (PeekChar ()))
  886. ReadAttributes ();
  887. if (PeekChar () == '/') {
  888. ReadChar ();
  889. isEmptyElement = true;
  890. depthDown = true;
  891. popScope = true;
  892. }
  893. else {
  894. elementStack.Push (name);
  895. baseURIStack.Push (attributes ["xml:base"] != null ?
  896. attributes ["xml:base"] : BaseURI);
  897. }
  898. Expect ('>');
  899. SetProperties (
  900. XmlNodeType.Element, // nodeType
  901. name, // name
  902. isEmptyElement, // isEmptyElement
  903. String.Empty, // value
  904. false // clearAttributes
  905. );
  906. if (!depthDown)
  907. ++depth;
  908. else
  909. depthDown = false;
  910. }
  911. // The reader is positioned on the first character
  912. // of the element's name.
  913. private void ReadEndTag ()
  914. {
  915. string name = ReadName ();
  916. if (elementStack.Count == 0)
  917. throw ReaderError("closing element without matching opening element");
  918. string expected = (string)elementStack.Pop();
  919. if (expected != name)
  920. throw ReaderError(String.Format ("unmatched closing element: expected {0} but found {1}", expected, name));
  921. baseURIStack.Pop ();
  922. SkipWhitespace ();
  923. Expect ('>');
  924. --depth;
  925. SetProperties (
  926. XmlNodeType.EndElement, // nodeType
  927. name, // name
  928. false, // isEmptyElement
  929. String.Empty, // value
  930. true // clearAttributes
  931. );
  932. popScope = true;
  933. }
  934. private void AppendNameChar (int ch)
  935. {
  936. CheckNameCapacity ();
  937. nameBuffer [nameLength++] = (char)ch;
  938. }
  939. private void CheckNameCapacity ()
  940. {
  941. if (nameLength == nameCapacity) {
  942. nameCapacity = nameCapacity * 2;
  943. char [] oldNameBuffer = nameBuffer;
  944. nameBuffer = new char [nameCapacity];
  945. Array.Copy (oldNameBuffer, nameBuffer, nameLength);
  946. }
  947. }
  948. private string CreateNameString ()
  949. {
  950. return parserContext.NameTable.Add (nameBuffer, 0, nameLength);
  951. }
  952. private void AppendValueChar (int ch)
  953. {
  954. CheckValueCapacity ();
  955. valueBuffer [valueLength++] = (char)ch;
  956. }
  957. private void CheckValueCapacity ()
  958. {
  959. if (valueLength == valueCapacity) {
  960. valueCapacity = valueCapacity * 2;
  961. char [] oldValueBuffer = valueBuffer;
  962. valueBuffer = new char [valueCapacity];
  963. Array.Copy (oldValueBuffer, valueBuffer, valueLength);
  964. }
  965. }
  966. private string CreateValueString ()
  967. {
  968. return new String (valueBuffer, 0, valueLength);
  969. }
  970. // The reader is positioned on the first character
  971. // of the text.
  972. private void ReadText (bool cleanValue)
  973. {
  974. if (cleanValue)
  975. valueLength = 0;
  976. int ch = PeekChar ();
  977. while (ch != '<' && ch != -1) {
  978. if (ch == '&') {
  979. ReadChar ();
  980. if (ReadReference (false))
  981. break;
  982. } else
  983. AppendValueChar (ReadChar ());
  984. ch = PeekChar ();
  985. }
  986. if (returnEntityReference && valueLength == 0) {
  987. SetEntityReferenceProperties ();
  988. } else {
  989. SetProperties (
  990. XmlNodeType.Text, // nodeType
  991. String.Empty, // name
  992. false, // isEmptyElement
  993. CreateValueString (), // value
  994. true // clearAttributes
  995. );
  996. }
  997. }
  998. // The leading '&' has already been consumed.
  999. // Returns true if the entity reference isn't a simple
  1000. // character reference or one of the predefined entities.
  1001. // This allows the ReadText method to break so that the
  1002. // next call to Read will return the EntityReference node.
  1003. private bool ReadReference (bool ignoreEntityReferences)
  1004. {
  1005. if (PeekChar () == '#') {
  1006. ReadChar ();
  1007. ReadCharacterReference ();
  1008. } else
  1009. ReadEntityReference (ignoreEntityReferences);
  1010. return returnEntityReference;
  1011. }
  1012. private void ReadCharacterReference ()
  1013. {
  1014. int value = 0;
  1015. if (PeekChar () == 'x') {
  1016. ReadChar ();
  1017. while (PeekChar () != ';' && PeekChar () != -1) {
  1018. int ch = ReadChar ();
  1019. if (ch >= '0' && ch <= '9')
  1020. value = (value << 4) + ch - '0';
  1021. else if (ch >= 'A' && ch <= 'F')
  1022. value = (value << 4) + ch - 'A' + 10;
  1023. else if (ch >= 'a' && ch <= 'f')
  1024. value = (value << 4) + ch - 'a' + 10;
  1025. else
  1026. throw ReaderError (
  1027. String.Format (
  1028. "invalid hexadecimal digit: {0} (#x{1:X})",
  1029. (char)ch,
  1030. ch));
  1031. }
  1032. } else {
  1033. while (PeekChar () != ';' && PeekChar () != -1) {
  1034. int ch = ReadChar ();
  1035. if (ch >= '0' && ch <= '9')
  1036. value = value * 10 + ch - '0';
  1037. else
  1038. throw ReaderError (
  1039. String.Format (
  1040. "invalid decimal digit: {0} (#x{1:X})",
  1041. (char)ch,
  1042. ch));
  1043. }
  1044. }
  1045. ReadChar (); // ';'
  1046. AppendValueChar (value);
  1047. }
  1048. private void ReadEntityReference (bool ignoreEntityReferences)
  1049. {
  1050. nameLength = 0;
  1051. int ch = PeekChar ();
  1052. while (ch != ';' && ch != -1) {
  1053. AppendNameChar (ReadChar ());
  1054. ch = PeekChar ();
  1055. }
  1056. Expect (';');
  1057. string name = CreateNameString ();
  1058. switch (name)
  1059. {
  1060. case "lt":
  1061. AppendValueChar ('<');
  1062. break;
  1063. case "gt":
  1064. AppendValueChar ('>');
  1065. break;
  1066. case "amp":
  1067. AppendValueChar ('&');
  1068. break;
  1069. case "apos":
  1070. AppendValueChar ('\'');
  1071. break;
  1072. case "quot":
  1073. AppendValueChar ('"');
  1074. break;
  1075. default:
  1076. if (ignoreEntityReferences) {
  1077. AppendValueChar ('&');
  1078. foreach (char ch2 in name) {
  1079. AppendValueChar (ch2);
  1080. }
  1081. AppendValueChar (';');
  1082. } else {
  1083. returnEntityReference = true;
  1084. entityReferenceName = name;
  1085. }
  1086. break;
  1087. }
  1088. }
  1089. // The reader is positioned on the first character of
  1090. // the attribute name.
  1091. private void ReadAttributes ()
  1092. {
  1093. do {
  1094. string name = ReadName ();
  1095. SkipWhitespace ();
  1096. Expect ('=');
  1097. SkipWhitespace ();
  1098. string value = ReadAttribute ();
  1099. SkipWhitespace ();
  1100. if (name == "xmlns")
  1101. parserContext.NamespaceManager.AddNamespace (String.Empty, UnescapeAttributeValue (value));
  1102. else if (name.StartsWith ("xmlns:"))
  1103. parserContext.NamespaceManager.AddNamespace (name.Substring (6), UnescapeAttributeValue (value));
  1104. AddAttribute (name, value);
  1105. } while (PeekChar () != '/' && PeekChar () != '>' && PeekChar () != -1);
  1106. }
  1107. // The reader is positioned on the quote character.
  1108. // *Keeps quote char* to value to get_QuoteChar() correctly.
  1109. private string ReadAttribute ()
  1110. {
  1111. valueLength = 0;
  1112. int quoteChar = ReadChar ();
  1113. if (quoteChar != '\'' && quoteChar != '\"')
  1114. throw ReaderError ("an attribute value was not quoted");
  1115. AppendValueChar (quoteChar);
  1116. while (PeekChar () != quoteChar) {
  1117. int ch = ReadChar ();
  1118. switch (ch)
  1119. {
  1120. case '<':
  1121. throw ReaderError ("attribute values cannot contain '<'");
  1122. case -1:
  1123. throw ReaderError ("unexpected end of file in an attribute value");
  1124. default:
  1125. AppendValueChar (ch);
  1126. break;
  1127. }
  1128. }
  1129. ReadChar (); // quoteChar
  1130. AppendValueChar (quoteChar);
  1131. return CreateValueString ();
  1132. }
  1133. // The reader is positioned on the first character
  1134. // of the target.
  1135. //
  1136. // Now it also reads XmlDeclaration, this method name became improper...
  1137. private void ReadProcessingInstruction ()
  1138. {
  1139. string target = ReadName ();
  1140. SkipWhitespace ();
  1141. valueLength = 0;
  1142. while (PeekChar () != -1) {
  1143. int ch = ReadChar ();
  1144. if (ch == '?' && PeekChar () == '>') {
  1145. ReadChar ();
  1146. break;
  1147. }
  1148. AppendValueChar ((char)ch);
  1149. }
  1150. SetProperties (
  1151. target == "xml" ?
  1152. XmlNodeType.XmlDeclaration :
  1153. XmlNodeType.ProcessingInstruction, // nodeType
  1154. target, // name
  1155. false, // isEmptyElement
  1156. CreateValueString (), // value
  1157. true // clearAttributes
  1158. );
  1159. }
  1160. // The reader is positioned on the first character after
  1161. // the leading '<!'.
  1162. private void ReadDeclaration ()
  1163. {
  1164. int ch = PeekChar ();
  1165. switch (ch)
  1166. {
  1167. case '-':
  1168. Expect ("--");
  1169. ReadComment ();
  1170. break;
  1171. case '[':
  1172. ReadChar ();
  1173. Expect ("CDATA[");
  1174. ReadCDATA ();
  1175. break;
  1176. case 'D':
  1177. Expect ("DOCTYPE");
  1178. ReadDoctypeDecl ();
  1179. break;
  1180. }
  1181. }
  1182. // The reader is positioned on the first character after
  1183. // the leading '<!--'.
  1184. private void ReadComment ()
  1185. {
  1186. valueLength = 0;
  1187. while (PeekChar () != -1) {
  1188. int ch = ReadChar ();
  1189. if (ch == '-' && PeekChar () == '-') {
  1190. ReadChar ();
  1191. if (PeekChar () != '>')
  1192. throw ReaderError ("comments cannot contain '--'");
  1193. ReadChar ();
  1194. break;
  1195. }
  1196. AppendValueChar ((char)ch);
  1197. }
  1198. SetProperties (
  1199. XmlNodeType.Comment, // nodeType
  1200. String.Empty, // name
  1201. false, // isEmptyElement
  1202. CreateValueString (), // value
  1203. true // clearAttributes
  1204. );
  1205. }
  1206. // The reader is positioned on the first character after
  1207. // the leading '<![CDATA['.
  1208. private void ReadCDATA ()
  1209. {
  1210. valueLength = 0;
  1211. bool skip = false;
  1212. int ch = 0;
  1213. while (PeekChar () != -1) {
  1214. if (!skip)
  1215. ch = ReadChar ();
  1216. skip = false;
  1217. if (ch == ']' && PeekChar () == ']') {
  1218. ch = ReadChar (); // ']'
  1219. if (PeekChar () == '>') {
  1220. ReadChar (); // '>'
  1221. break;
  1222. } else {
  1223. skip = true;
  1224. // AppendValueChar (']');
  1225. // AppendValueChar (']');
  1226. // ch = ReadChar ();
  1227. }
  1228. }
  1229. AppendValueChar ((char)ch);
  1230. }
  1231. SetProperties (
  1232. XmlNodeType.CDATA, // nodeType
  1233. String.Empty, // name
  1234. false, // isEmptyElement
  1235. CreateValueString (), // value
  1236. true // clearAttributes
  1237. );
  1238. }
  1239. // The reader is positioned on the first character after
  1240. // the leading '<!DOCTYPE'.
  1241. private void ReadDoctypeDecl ()
  1242. {
  1243. string doctypeName = null;
  1244. string publicId = String.Empty;
  1245. string systemId = String.Empty;
  1246. int intSubsetStartLine = 0;
  1247. int intSubsetStartColumn = 0;
  1248. SkipWhitespace ();
  1249. doctypeName = ReadName ();
  1250. SkipWhitespace ();
  1251. switch(PeekChar ())
  1252. {
  1253. case 'S':
  1254. systemId = ReadSystemLiteral (true);
  1255. break;
  1256. case 'P':
  1257. publicId = ReadPubidLiteral ();
  1258. SkipWhitespace ();
  1259. systemId = ReadSystemLiteral (false);
  1260. break;
  1261. }
  1262. SkipWhitespace ();
  1263. if(PeekChar () == '[')
  1264. {
  1265. // read markupdecl etc. or end of decl
  1266. ReadChar ();
  1267. intSubsetStartLine = this.LineNumber;
  1268. intSubsetStartColumn = this.LinePosition;
  1269. int startPos = currentTag.Length;
  1270. // do {
  1271. ReadInternalSubset ();
  1272. // } while (nodeType != XmlNodeType.None);
  1273. int endPos = currentTag.Length - 1;
  1274. parserContext.InternalSubset = currentTag.ToString (startPos, endPos - startPos);
  1275. }
  1276. // end of DOCTYPE decl.
  1277. SkipWhitespace ();
  1278. Expect ('>');
  1279. // now compile DTD
  1280. currentSubset = new DTDObjectModel (); // merges both internal and external subsets in the meantime,
  1281. int originalParserDepth = parserInputStack.Count;
  1282. if (intSubsetStartLine > 0) {
  1283. XmlParserInput original = currentInput;
  1284. currentInput = new XmlParserInput (new StringReader (parserContext.InternalSubset), BaseURI, intSubsetStartLine, intSubsetStartColumn);
  1285. do {
  1286. CompileDTDSubset ();
  1287. if (PeekChar () == -1 && parserInputStack.Count > 0)
  1288. popParserInput ();
  1289. } while (nodeType != XmlNodeType.None || parserInputStack.Count > originalParserDepth);
  1290. if (dtdIncludeSect != 0)
  1291. this.ReaderError ("INCLUDE section is not ended correctly.");
  1292. currentInput = original;
  1293. }
  1294. if (systemId != String.Empty) {
  1295. pushParserInput (systemId);
  1296. do {
  1297. this.CompileDTDSubset ();
  1298. if (PeekChar () == -1 && parserInputStack.Count > 1)
  1299. popParserInput ();
  1300. } while (nodeType != XmlNodeType.None || parserInputStack.Count > originalParserDepth + 1);
  1301. popParserInput ();
  1302. }
  1303. // set properties for <!DOCTYPE> node
  1304. SetProperties (
  1305. XmlNodeType.DocumentType, // nodeType
  1306. doctypeName, // name
  1307. false, // isEmptyElement
  1308. parserContext.InternalSubset, // value
  1309. true // clearAttributes
  1310. );
  1311. }
  1312. private void pushParserInput (string url)
  1313. {
  1314. string absPath = null;
  1315. #if NetworkEnabled
  1316. try {
  1317. Uri baseUrl = new Uri (BaseURI);
  1318. absPath = resolver.ResolveUri (baseUrl, url).ToString ();
  1319. } catch (UriFormatException) {
  1320. if (Path.IsPathRooted (url))
  1321. absPath = url;
  1322. else if (BaseURI != String.Empty)
  1323. absPath = new FileInfo (BaseURI).DirectoryName + Path.DirectorySeparatorChar + url;
  1324. else
  1325. absPath = url;
  1326. }
  1327. #else
  1328. if (Path.IsPathRooted (url))
  1329. absPath = url;
  1330. else if (BaseURI != String.Empty)
  1331. absPath = new FileInfo (BaseURI).DirectoryName + Path.DirectorySeparatorChar + url;
  1332. else
  1333. absPath = url;
  1334. #endif
  1335. foreach (XmlParserInput i in parserInputStack.ToArray ()) {
  1336. if (i.BaseURI == url)
  1337. this.ReaderError ("Nested inclusion is not allowed: " + url);
  1338. }
  1339. parserInputStack.Push (currentInput);
  1340. currentInput = new XmlParserInput (new XmlStreamReader (absPath, false), absPath);
  1341. baseURIStack.Push (BaseURI);
  1342. parserContext.BaseURI = absPath;
  1343. }
  1344. private void popParserInput ()
  1345. {
  1346. currentInput = parserInputStack.Pop () as XmlParserInput;
  1347. parserContext.BaseURI = this.baseURIStack.Pop () as string;
  1348. }
  1349. private enum DtdInputState
  1350. {
  1351. Free = 1,
  1352. ElementDecl,
  1353. AttlistDecl,
  1354. EntityDecl,
  1355. NotationDecl,
  1356. PI,
  1357. Comment,
  1358. InsideSingleQuoted,
  1359. InsideDoubleQuoted,
  1360. }
  1361. private class DtdInputStateStack
  1362. {
  1363. Stack intern = new Stack ();
  1364. public DtdInputStateStack ()
  1365. {
  1366. Push (DtdInputState.Free);
  1367. }
  1368. public DtdInputState Peek ()
  1369. {
  1370. return (DtdInputState) intern.Peek ();
  1371. }
  1372. public DtdInputState Pop ()
  1373. {
  1374. return (DtdInputState) intern.Pop ();
  1375. }
  1376. public void Push (DtdInputState val)
  1377. {
  1378. intern.Push (val);
  1379. }
  1380. }
  1381. DtdInputStateStack stateStack = new DtdInputStateStack ();
  1382. DtdInputState State {
  1383. get { return stateStack.Peek (); }
  1384. }
  1385. // Simply read but not generate any result.
  1386. private void ReadInternalSubset ()
  1387. {
  1388. bool continueParse = true;
  1389. while (continueParse) {
  1390. switch (ReadChar ()) {
  1391. case ']':
  1392. switch (State) {
  1393. case DtdInputState.Free:
  1394. continueParse = false;
  1395. break;
  1396. case DtdInputState.InsideDoubleQuoted:
  1397. continue;
  1398. case DtdInputState.InsideSingleQuoted:
  1399. continue;
  1400. default:
  1401. throw ReaderError ("unexpected end of file at DTD.");
  1402. }
  1403. break;
  1404. case -1:
  1405. throw ReaderError ("unexpected end of file at DTD.");
  1406. case '<':
  1407. if (State == DtdInputState.InsideDoubleQuoted ||
  1408. State == DtdInputState.InsideSingleQuoted)
  1409. continue; // well-formed
  1410. switch (ReadChar ()) {
  1411. case '?':
  1412. stateStack.Push (DtdInputState.PI);
  1413. break;
  1414. case '!':
  1415. switch (ReadChar ()) {
  1416. case 'E':
  1417. switch (ReadChar ()) {
  1418. case 'L':
  1419. Expect ("EMENT");
  1420. stateStack.Push (DtdInputState.ElementDecl);
  1421. break;
  1422. case 'N':
  1423. Expect ("TITY");
  1424. stateStack.Push (DtdInputState.EntityDecl);
  1425. break;
  1426. default:
  1427. throw ReaderError ("unexpected token '<!E'.");
  1428. }
  1429. break;
  1430. case 'A':
  1431. Expect ("TTLIST");
  1432. stateStack.Push (DtdInputState.AttlistDecl);
  1433. break;
  1434. case 'N':
  1435. Expect ("OTATION");
  1436. stateStack.Push (DtdInputState.NotationDecl);
  1437. break;
  1438. case '-':
  1439. Expect ("-");
  1440. stateStack.Push (DtdInputState.Comment);
  1441. break;
  1442. }
  1443. break;
  1444. default:
  1445. throw ReaderError ("unexpected '>'.");
  1446. }
  1447. break;
  1448. case '\'':
  1449. if (State == DtdInputState.InsideSingleQuoted)
  1450. stateStack.Pop ();
  1451. else if (State != DtdInputState.InsideDoubleQuoted && State != DtdInputState.Comment)
  1452. stateStack.Push (DtdInputState.InsideSingleQuoted);
  1453. break;
  1454. case '"':
  1455. if (State == DtdInputState.InsideDoubleQuoted)
  1456. stateStack.Pop ();
  1457. else if (State != DtdInputState.InsideSingleQuoted && State != DtdInputState.Comment)
  1458. stateStack.Push (DtdInputState.InsideDoubleQuoted);
  1459. break;
  1460. case '>':
  1461. switch (State) {
  1462. case DtdInputState.ElementDecl:
  1463. goto case DtdInputState.NotationDecl;
  1464. case DtdInputState.AttlistDecl:
  1465. goto case DtdInputState.NotationDecl;
  1466. case DtdInputState.EntityDecl:
  1467. goto case DtdInputState.NotationDecl;
  1468. case DtdInputState.NotationDecl:
  1469. stateStack.Pop ();
  1470. break;
  1471. case DtdInputState.InsideDoubleQuoted:
  1472. continue;
  1473. case DtdInputState.InsideSingleQuoted:
  1474. continue; // well-formed
  1475. case DtdInputState.Comment:
  1476. continue;
  1477. default:
  1478. throw ReaderError ("unexpected token '>'");
  1479. }
  1480. break;
  1481. case '?':
  1482. if (State == DtdInputState.PI) {
  1483. if (ReadChar () == '>')
  1484. stateStack.Pop ();
  1485. }
  1486. break;
  1487. case '-':
  1488. if (State == DtdInputState.Comment) {
  1489. if (PeekChar () == '-') {
  1490. ReadChar ();
  1491. Expect ('>');
  1492. stateStack.Pop ();
  1493. }
  1494. }
  1495. break;
  1496. case '%':
  1497. if (State != DtdInputState.Free && State != DtdInputState.EntityDecl && State != DtdInputState.Comment && State != DtdInputState.InsideDoubleQuoted && State != DtdInputState.InsideSingleQuoted)
  1498. throw ReaderError ("Parameter Entity Reference cannot appear as a part of markupdecl (see XML spec 2.8).");
  1499. break;
  1500. }
  1501. }
  1502. }
  1503. // Read any one of following:
  1504. // elementdecl, AttlistDecl, EntityDecl, NotationDecl,
  1505. // PI, Comment, Parameter Entity, or doctype termination char(']')
  1506. //
  1507. // returns a node of some nodeType or null, setting nodeType.
  1508. // (if None then ']' was found.)
  1509. private void CompileDTDSubset()
  1510. {
  1511. SkipWhitespace ();
  1512. switch(PeekChar ())
  1513. {
  1514. case -1:
  1515. nodeType = XmlNodeType.None;
  1516. break;
  1517. case '%':
  1518. TryExpandPERef ();
  1519. break;
  1520. case '<':
  1521. ReadChar ();
  1522. switch(ReadChar ())
  1523. {
  1524. case '?':
  1525. // Only read, no store.
  1526. ReadProcessingInstruction ();
  1527. break;
  1528. case '!':
  1529. CompileDeclaration ();
  1530. break;
  1531. default:
  1532. throw ReaderError ("Syntax Error after '<' character.");
  1533. }
  1534. break;
  1535. case ']':
  1536. // End of inclusion
  1537. Expect ("]]>");
  1538. dtdIncludeSect--;
  1539. SkipWhitespace ();
  1540. break;
  1541. default:
  1542. throw ReaderError (String.Format ("Syntax Error inside doctypedecl markup : {0}({1})", PeekChar (), (char) PeekChar ()));
  1543. }
  1544. }
  1545. private void CompileDeclaration ()
  1546. {
  1547. nodeType = XmlNodeType.DocumentType; // Hack!!
  1548. switch(ReadChar ())
  1549. {
  1550. case '-':
  1551. Expect ('-');
  1552. // Only read, no store.
  1553. ReadComment ();
  1554. break;
  1555. case 'E':
  1556. switch(ReadChar ())
  1557. {
  1558. case 'N':
  1559. Expect ("TITY");
  1560. SkipWhitespace ();
  1561. LOOPBACK:
  1562. if (PeekChar () == '%') {
  1563. ReadChar ();
  1564. if (!XmlConstructs.IsSpace (PeekChar ())) {
  1565. ExpandPERef ();
  1566. goto LOOPBACK;
  1567. // throw ReaderError ("expected whitespace between '%' and name.");
  1568. } else {
  1569. SkipWhitespace ();
  1570. TryExpandPERef ();
  1571. if (XmlConstructs.IsName (PeekChar ()))
  1572. ReadParameterEntityDecl ();
  1573. else
  1574. throw ReaderError ("expected name character");
  1575. }
  1576. break;
  1577. }
  1578. DTDEntityDeclaration ent = ReadEntityDecl ();
  1579. if (currentSubset.EntityDecls [ent.Name] == null)
  1580. currentSubset.EntityDecls.Add (ent.Name, ent);
  1581. break;
  1582. case 'L':
  1583. Expect ("EMENT");
  1584. DTDElementDeclaration el = ReadElementDecl ();
  1585. currentSubset.ElementDecls.Add (el.Name, el);
  1586. break;
  1587. default:
  1588. throw ReaderError ("Syntax Error after '<!E' (ELEMENT or ENTITY must be found)");
  1589. }
  1590. break;
  1591. case 'A':
  1592. Expect ("TTLIST");
  1593. DTDAttListDeclaration atl = ReadAttListDecl ();
  1594. if (currentSubset.AttListDecls.ContainsKey (atl.Name))
  1595. currentSubset.AttListDecls.Add (atl.Name, atl);
  1596. break;
  1597. case 'N':
  1598. Expect ("OTATION");
  1599. DTDNotationDeclaration not = ReadNotationDecl ();
  1600. currentSubset.NotationDecls.Add (not.Name, not);
  1601. break;
  1602. case '[':
  1603. // conditional sections
  1604. SkipWhitespace ();
  1605. TryExpandPERef ();
  1606. SkipWhitespace ();
  1607. Expect ('I');
  1608. switch (ReadChar ()) {
  1609. case 'N':
  1610. Expect ("CLUDE");
  1611. SkipWhitespace ();
  1612. Expect ('[');
  1613. dtdIncludeSect++;
  1614. break;
  1615. case 'G':
  1616. Expect ("NORE");
  1617. ReadIgnoreSect ();
  1618. break;
  1619. }
  1620. break;
  1621. default:
  1622. throw ReaderError ("Syntax Error after '<!' characters.");
  1623. }
  1624. }
  1625. private void ReadIgnoreSect ()
  1626. {
  1627. bool skip = false;
  1628. SkipWhitespace ();
  1629. Expect ('[');
  1630. int dtdIgnoreSect = 1;
  1631. while (dtdIgnoreSect > 0) {
  1632. switch (skip ? PeekChar () : ReadChar ()) {
  1633. case -1:
  1634. throw ReaderError ("Unexpected IGNORE section end.");
  1635. break;
  1636. case '<':
  1637. if (ReadChar () == '!' && ReadChar () == '[')
  1638. dtdIgnoreSect++;
  1639. break;
  1640. case ']':
  1641. if (ReadChar () == ']') {
  1642. if (ReadChar () == '>')
  1643. dtdIgnoreSect--;
  1644. else
  1645. skip = true;
  1646. }
  1647. break;
  1648. }
  1649. skip = false;
  1650. }
  1651. }
  1652. // The reader is positioned on the head of the name.
  1653. private DTDElementDeclaration ReadElementDecl ()
  1654. {
  1655. DTDElementDeclaration decl = new DTDElementDeclaration ();
  1656. SkipWhitespace ();
  1657. TryExpandPERef ();
  1658. decl.Name = ReadName ();
  1659. SkipWhitespace ();
  1660. TryExpandPERef ();
  1661. ReadContentSpec (decl);
  1662. SkipWhitespace ();
  1663. Expect ('>');
  1664. return decl;
  1665. }
  1666. // read 'children'(BNF) of contentspec
  1667. private void ReadContentSpec (DTDElementDeclaration decl)
  1668. {
  1669. switch(PeekChar ())
  1670. {
  1671. case 'E':
  1672. decl.IsEmpty = true;
  1673. Expect ("EMPTY");
  1674. break;
  1675. case 'A':
  1676. decl.IsAny = true;
  1677. Expect ("ANY");
  1678. break;
  1679. case '(':
  1680. DTDContentModel model = decl.ContentModel;
  1681. ReadChar ();
  1682. SkipWhitespace ();
  1683. TryExpandPERef ();
  1684. if(PeekChar () == '#') {
  1685. // Mixed Contents
  1686. decl.IsMixedContent = true;
  1687. Expect ("#PCDATA");
  1688. SkipWhitespace ();
  1689. TryExpandPERef ();
  1690. SkipWhitespace ();
  1691. while(PeekChar () != ')') {
  1692. Expect('|');
  1693. SkipWhitespace ();
  1694. TryExpandPERef ();
  1695. SkipWhitespace ();
  1696. model.ChildModels.Add (ReadName ());
  1697. SkipWhitespace ();
  1698. TryExpandPERef ();
  1699. }
  1700. Expect (')');
  1701. if(PeekChar () == '*')
  1702. ReadChar (); // ZeroOrMore
  1703. } else {
  1704. // Non-Mixed Contents
  1705. model.ChildModels.Add (ReadCP ());
  1706. SkipWhitespace ();
  1707. do { // copied from ReadCP() ...;-)
  1708. TryExpandPERef ();
  1709. SkipWhitespace ();
  1710. if(PeekChar ()=='|') {
  1711. // CPType=Or
  1712. model.OrderType = DTDContentOrderType.Or;
  1713. ReadChar ();
  1714. SkipWhitespace ();
  1715. model.ChildModels.Add (ReadCP ());
  1716. SkipWhitespace ();
  1717. }
  1718. else if(PeekChar () == ',')
  1719. {
  1720. // CPType=Seq
  1721. model.OrderType = DTDContentOrderType.Seq;
  1722. ReadChar ();
  1723. SkipWhitespace ();
  1724. model.ChildModels.Add (ReadCP ());
  1725. SkipWhitespace ();
  1726. }
  1727. else
  1728. break;
  1729. }
  1730. while(true);
  1731. Expect (')');
  1732. switch(PeekChar ())
  1733. {
  1734. case '?':
  1735. model.MinOccurs = 0;
  1736. ReadChar ();
  1737. break;
  1738. case '*':
  1739. model.MinOccurs = 0;
  1740. model.MaxOccurs = decimal.MaxValue;
  1741. ReadChar ();
  1742. break;
  1743. case '+':
  1744. model.MaxOccurs = decimal.MaxValue;
  1745. ReadChar ();
  1746. break;
  1747. }
  1748. SkipWhitespace ();
  1749. }
  1750. SkipWhitespace ();
  1751. break;
  1752. }
  1753. }
  1754. // Read 'cp' (BNF) of contentdecl (BNF)
  1755. private DTDContentModel ReadCP ()
  1756. {
  1757. DTDContentModel model = new DTDContentModel ();
  1758. TryExpandPERef ();
  1759. if(PeekChar () == '(') {
  1760. ReadChar ();
  1761. SkipWhitespace ();
  1762. model.ChildModels.Add (ReadCP ());
  1763. SkipWhitespace ();
  1764. do {
  1765. TryExpandPERef ();
  1766. SkipWhitespace ();
  1767. if(PeekChar ()=='|') {
  1768. // CPType=Or
  1769. model.OrderType = DTDContentOrderType.Or;
  1770. ReadChar ();
  1771. SkipWhitespace ();
  1772. model.ChildModels.Add (ReadCP ());
  1773. SkipWhitespace ();
  1774. }
  1775. else if(PeekChar () == ',') {
  1776. // CPType=Seq
  1777. model.OrderType = DTDContentOrderType.Seq;
  1778. ReadChar ();
  1779. SkipWhitespace ();
  1780. model.ChildModels.Add (ReadCP ());
  1781. SkipWhitespace ();
  1782. }
  1783. else
  1784. break;
  1785. }
  1786. while(true);
  1787. SkipWhitespace ();
  1788. Expect (')');
  1789. }
  1790. else {
  1791. TryExpandPERef ();
  1792. model.ElementName = ReadName ();
  1793. }
  1794. switch(PeekChar ()) {
  1795. case '?':
  1796. model.MinOccurs = 0;
  1797. ReadChar ();
  1798. break;
  1799. case '*':
  1800. model.MinOccurs = 0;
  1801. model.MaxOccurs = decimal.MaxValue;
  1802. ReadChar ();
  1803. break;
  1804. case '+':
  1805. model.MaxOccurs = decimal.MaxValue;
  1806. ReadChar ();
  1807. break;
  1808. }
  1809. return model;
  1810. }
  1811. // The reader is positioned on the first name char.
  1812. private void ReadParameterEntityDecl ()
  1813. {
  1814. DTDParameterEntityDeclaration decl =
  1815. new DTDParameterEntityDeclaration();
  1816. decl.BaseURI = BaseURI;
  1817. decl.Name = ReadName ();
  1818. SkipWhitespace ();
  1819. if (PeekChar () == 'S' || PeekChar () == 'P') {
  1820. // throw new NotImplementedException ("External parameter entity reference is not implemented yet.");
  1821. // read publicId/systemId
  1822. ReadExternalID ();
  1823. decl.PublicId = attributes ["PUBLIC"] as string;
  1824. decl.SystemId = attributes ["SYSTEM"] as string;
  1825. SkipWhitespace ();
  1826. }
  1827. else {
  1828. TryExpandPERef ();
  1829. int quoteChar = ReadChar ();
  1830. int start = currentTag.Length;
  1831. while (true) {
  1832. SkipWhitespace ();
  1833. int c = PeekChar ();
  1834. if ((int) c == -1)
  1835. throw new XmlException ("unexpected end of stream in entity value definition.");
  1836. switch (c) {
  1837. case '"':
  1838. ReadChar ();
  1839. if (quoteChar == '"') goto SKIP;
  1840. break;
  1841. case '\'':
  1842. ReadChar ();
  1843. if (quoteChar == '\'') goto SKIP;
  1844. break;
  1845. case '%':
  1846. ImportAsPERef ();
  1847. break;
  1848. default:
  1849. ReadChar ();
  1850. break;
  1851. }
  1852. }
  1853. SKIP:
  1854. decl.Value = currentTag.ToString (start, currentTag.Length - start - 1);
  1855. }
  1856. SkipWhitespace ();
  1857. Expect ('>');
  1858. if (parameterEntities [decl.Name] == null) {
  1859. parameterEntities.Add (decl.Name, decl);
  1860. }
  1861. }
  1862. // reader is positioned on '%'
  1863. private void ImportAsPERef ()
  1864. {
  1865. StringBuilder sb = null;
  1866. int peRefStart = currentTag.Length;
  1867. string appendStr = "";
  1868. ReadChar ();
  1869. string peName = ReadName ();
  1870. Expect (';');
  1871. DTDParameterEntityDeclaration peDecl =
  1872. this.parameterEntities [peName] as DTDParameterEntityDeclaration;
  1873. if (peDecl == null)
  1874. throw ReaderError ("Parameter entity " + peName + " not found.");
  1875. if (peDecl.SystemId != null) {
  1876. pushParserInput (peDecl.SystemId);
  1877. if (sb == null)
  1878. sb = new StringBuilder ();
  1879. else
  1880. sb.Length = 0;
  1881. while (PeekChar () != -1)
  1882. sb.Append (ReadChar ());
  1883. popParserInput ();
  1884. appendStr = sb.ToString ();
  1885. } else {
  1886. appendStr = peDecl.Value;
  1887. }
  1888. currentTag.Remove (peRefStart,
  1889. currentTag.Length - peRefStart);
  1890. currentTag.Append (Dereference (appendStr));
  1891. }
  1892. // The reader is positioned on the head of the name.
  1893. private DTDEntityDeclaration ReadEntityDecl ()
  1894. {
  1895. DTDEntityDeclaration decl = new DTDEntityDeclaration ();
  1896. decl.Name = ReadName ();
  1897. SkipWhitespace ();
  1898. TryExpandPERef ();
  1899. SkipWhitespace ();
  1900. if (PeekChar () == 'S' || PeekChar () == 'P') {
  1901. // external entity
  1902. ReadExternalID ();
  1903. decl.PublicId = attributes ["PUBLIC"] as string;
  1904. decl.SystemId = attributes ["SYSTEM"] as string;
  1905. SkipWhitespace ();
  1906. if (PeekChar () == 'N')
  1907. {
  1908. // NDataDecl
  1909. Expect ("NDATA");
  1910. SkipWhitespace ();
  1911. decl.NotationName = ReadName (); // ndata_name
  1912. }
  1913. }
  1914. else {
  1915. // general entity
  1916. decl.EntityValue = ReadEntityValueDecl ();
  1917. }
  1918. SkipWhitespace ();
  1919. Expect ('>');
  1920. return decl;
  1921. }
  1922. private string ReadEntityValueDecl ()
  1923. {
  1924. SkipWhitespace ();
  1925. // quotation char will be finally removed on unescaping
  1926. int quoteChar = ReadChar ();
  1927. int start = currentTag.Length;
  1928. if (quoteChar != '\'' && quoteChar != '"')
  1929. throw new XmlException ("quotation char was expected.");
  1930. while (PeekChar () != quoteChar) {
  1931. switch (PeekChar ()) {
  1932. case '%':
  1933. this.ImportAsPERef ();
  1934. continue;
  1935. case '&':
  1936. ReadChar ();
  1937. // Expect ('#');
  1938. // ReadCharacterReference ();
  1939. ReadReference (true);
  1940. break;
  1941. case -1:
  1942. throw new XmlException ("unexpected end of stream.");
  1943. default:
  1944. ReadChar ();
  1945. break;
  1946. }
  1947. }
  1948. string value = Dereference (currentTag.ToString (start, currentTag.Length - start));
  1949. Expect (quoteChar);
  1950. return value;
  1951. }
  1952. private DTDAttListDeclaration ReadAttListDecl ()
  1953. {
  1954. SkipWhitespace ();
  1955. TryExpandPERef ();
  1956. string name = ReadName (); // target element name
  1957. DTDAttListDeclaration decl =
  1958. currentSubset.AttListDecls [name] as DTDAttListDeclaration;
  1959. if (decl == null)
  1960. decl = new DTDAttListDeclaration ();
  1961. decl.Name = name;
  1962. SkipWhitespace ();
  1963. TryExpandPERef ();
  1964. SkipWhitespace ();
  1965. while (XmlConstructs.IsName ((char) PeekChar ())) {
  1966. DTDAttributeDefinition def = ReadAttributeDefinition ();
  1967. if (decl.AttributeDefinitions [def.Name] == null)
  1968. decl.AttributeDefinitions.Add (def.Name, def);
  1969. SkipWhitespace ();
  1970. TryExpandPERef ();
  1971. SkipWhitespace ();
  1972. }
  1973. SkipWhitespace ();
  1974. Expect ('>');
  1975. return decl;
  1976. }
  1977. private DTDAttributeDefinition ReadAttributeDefinition ()
  1978. {
  1979. DTDAttributeDefinition def = new DTDAttributeDefinition ();
  1980. // attr_name
  1981. TryExpandPERef ();
  1982. def.Name = ReadName ();
  1983. SkipWhitespace ();
  1984. // attr_value
  1985. TryExpandPERef ();
  1986. switch(PeekChar ()) {
  1987. case 'C': // CDATA
  1988. Expect ("CDATA");
  1989. def.AttributeType = DTDAttributeType.CData;
  1990. break;
  1991. case 'I': // ID, IDREF, IDREFS
  1992. Expect ("ID");
  1993. if(PeekChar () == 'R') {
  1994. Expect ("REF");
  1995. if(PeekChar () == 'S') {
  1996. // IDREFS
  1997. ReadChar ();
  1998. def.AttributeType = DTDAttributeType.IdRefs;
  1999. }
  2000. else // IDREF
  2001. def.AttributeType = DTDAttributeType.IdRef;
  2002. }
  2003. else // ID
  2004. def.AttributeType = DTDAttributeType.Id;
  2005. break;
  2006. case 'E': // ENTITY, ENTITIES
  2007. Expect ("ENTIT");
  2008. switch(ReadChar ()) {
  2009. case 'Y': // ENTITY
  2010. def.AttributeType = DTDAttributeType.Entity;
  2011. break;
  2012. case 'I': // ENTITIES
  2013. Expect ("ES");
  2014. def.AttributeType = DTDAttributeType.Entities;
  2015. break;
  2016. }
  2017. break;
  2018. case 'N': // NMTOKEN, NMTOKENS, NOTATION
  2019. ReadChar ();
  2020. switch(PeekChar ()) {
  2021. case 'M':
  2022. Expect ("MTOKEN");
  2023. if(PeekChar ()=='S') { // NMTOKENS
  2024. ReadChar ();
  2025. def.AttributeType = DTDAttributeType.NmTokens;
  2026. }
  2027. else // NMTOKEN
  2028. def.AttributeType = DTDAttributeType.NmToken;
  2029. break;
  2030. case 'O':
  2031. Expect ("OTATION");
  2032. def.AttributeType = DTDAttributeType.Notation;
  2033. SkipWhitespace ();
  2034. Expect ('(');
  2035. SkipWhitespace ();
  2036. def.EnumeratedNotations.Add (ReadName ()); // notation name
  2037. SkipWhitespace ();
  2038. while(PeekChar () == '|') {
  2039. ReadChar ();
  2040. SkipWhitespace ();
  2041. def.EnumeratedNotations.Add (ReadName ()); // notation name
  2042. SkipWhitespace ();
  2043. }
  2044. Expect (')');
  2045. break;
  2046. default:
  2047. throw new XmlException ("attribute declaration syntax error.");
  2048. }
  2049. break;
  2050. default: // Enumerated Values
  2051. TryExpandPERef ();
  2052. Expect ('(');
  2053. SkipWhitespace ();
  2054. def.EnumeratedAttributeDeclaration.Add (ReadNmToken ()); // enum value
  2055. SkipWhitespace ();
  2056. while(PeekChar () == '|') {
  2057. ReadChar ();
  2058. SkipWhitespace ();
  2059. def.EnumeratedAttributeDeclaration.Add (ReadNmToken ()); // enum value
  2060. SkipWhitespace ();
  2061. }
  2062. Expect (')');
  2063. break;
  2064. }
  2065. SkipWhitespace ();
  2066. TryExpandPERef ();
  2067. // def_value
  2068. if(PeekChar () == '#')
  2069. {
  2070. ReadChar ();
  2071. switch(PeekChar ())
  2072. {
  2073. case 'R':
  2074. Expect ("REQUIRED");
  2075. def.OccurenceType = DTDAttributeOccurenceType.Required;
  2076. break;
  2077. case 'I':
  2078. Expect ("IMPLIED");
  2079. def.OccurenceType = DTDAttributeOccurenceType.Optional;
  2080. break;
  2081. case 'F':
  2082. Expect ("FIXED");
  2083. def.OccurenceType = DTDAttributeOccurenceType.Fixed;
  2084. SkipWhitespace ();
  2085. def.UnresolvedDefaultValue = ReadAttribute ();
  2086. break;
  2087. }
  2088. } else {
  2089. // one of the enumerated value
  2090. if (PeekChar () == -1) {
  2091. popParserInput ();
  2092. }
  2093. SkipWhitespace ();
  2094. def.UnresolvedDefaultValue = ReadAttribute ();
  2095. }
  2096. return def;
  2097. }
  2098. private DTDNotationDeclaration ReadNotationDecl()
  2099. {
  2100. DTDNotationDeclaration decl = new DTDNotationDeclaration ();
  2101. SkipWhitespace ();
  2102. decl.Name = ReadName (); // notation name
  2103. if (namespaces) { // copy from SetProperties ;-)
  2104. int indexOfColon = decl.Name.IndexOf (':');
  2105. if (indexOfColon == -1) {
  2106. decl.Prefix = String.Empty;
  2107. decl.LocalName = decl.Name;
  2108. } else {
  2109. decl.Prefix = decl.Name.Substring (0, indexOfColon);
  2110. decl.LocalName = decl.Name.Substring (indexOfColon + 1);
  2111. }
  2112. } else {
  2113. decl.Prefix = String.Empty;
  2114. decl.LocalName = decl.Name;
  2115. }
  2116. SkipWhitespace ();
  2117. if(PeekChar () == 'P') {
  2118. decl.PublicId = ReadPubidLiteral ();
  2119. SkipWhitespace ();
  2120. if (PeekChar () == '\'' || PeekChar () == '"') {
  2121. decl.SystemId = ReadSystemLiteral (false);
  2122. SkipWhitespace ();
  2123. }
  2124. } else if(PeekChar () == 'S') {
  2125. decl.SystemId = ReadSystemLiteral (true);
  2126. SkipWhitespace ();
  2127. }
  2128. if(decl.PublicId == null && decl.SystemId == null)
  2129. throw new XmlException ("public or system declaration required for \"NOTATION\" declaration.");
  2130. Expect ('>');
  2131. return decl;
  2132. }
  2133. private void TryExpandPERef ()
  2134. {
  2135. if (PeekChar () == '%') {
  2136. ReadChar ();
  2137. if (!XmlConstructs.IsName (PeekChar ()))
  2138. return;
  2139. ExpandPERef ();
  2140. }
  2141. }
  2142. // reader is positioned on the first letter of the name.
  2143. private void ExpandPERef ()
  2144. {
  2145. ExpandPERef (true);
  2146. }
  2147. private void ExpandPERef (bool attachSpace)
  2148. {
  2149. string peName = ReadName ();
  2150. Expect (";");
  2151. ExpandNamedPERef (peName, attachSpace);
  2152. }
  2153. private void ExpandNamedPERef (string peName, bool attachSpace)
  2154. {
  2155. DTDParameterEntityDeclaration decl =
  2156. parameterEntities [peName] as DTDParameterEntityDeclaration;
  2157. if (decl == null)
  2158. throw new XmlException ("undeclared parameter entity: '" + peName + "'");
  2159. if (decl.SystemId != null) {
  2160. pushParserInput (decl.SystemId);
  2161. }
  2162. // add buffer
  2163. else
  2164. currentInput.InsertParameterEntityBuffer (attachSpace ? " " + Dereference (decl.Value) + " " : decl.Value);
  2165. SkipWhitespace (); // is it ok?
  2166. // while (PeekChar () == '%')
  2167. // TryExpandPERef (); // recursive
  2168. }
  2169. private void ReadExternalID() {
  2170. switch(PeekChar ()) {
  2171. case 'S':
  2172. attributes ["PUBLIC"] = null;
  2173. attributes ["SYSTEM"] = ReadSystemLiteral (true);
  2174. break;
  2175. case 'P':
  2176. attributes ["PUBLIC"] = ReadPubidLiteral ();
  2177. SkipWhitespace ();
  2178. attributes ["SYSTEM"] = ReadSystemLiteral (false);
  2179. break;
  2180. }
  2181. }
  2182. // The reader is positioned on the first 'S' of "SYSTEM".
  2183. private string ReadSystemLiteral (bool expectSYSTEM)
  2184. {
  2185. if(expectSYSTEM)
  2186. Expect ("SYSTEM");
  2187. SkipWhitespace ();
  2188. int quoteChar = ReadChar (); // apos or quot
  2189. int startPos = currentTag.Length;
  2190. int c = 0;
  2191. while(c != quoteChar) {
  2192. c = ReadChar ();
  2193. if(c < 0) throw ReaderError ("Unexpected end of stream in ExternalID.");
  2194. }
  2195. return currentTag.ToString (startPos, currentTag.Length - 1 - startPos);
  2196. }
  2197. private string ReadPubidLiteral()
  2198. {
  2199. Expect ("PUBLIC");
  2200. SkipWhitespace ();
  2201. int quoteChar = ReadChar ();
  2202. int startPos = currentTag.Length;
  2203. int c = 0;
  2204. while(c != quoteChar)
  2205. {
  2206. c = ReadChar ();
  2207. if(c < 0) throw ReaderError ("Unexpected end of stream in ExternalID.");
  2208. if(c != quoteChar && !XmlConstructs.IsPubid (c))
  2209. throw ReaderError("character '" + (char)c + "' not allowed for PUBLIC ID");
  2210. }
  2211. return currentTag.ToString (startPos, currentTag.Length - 1 - startPos);
  2212. }
  2213. // The reader is positioned on the first character
  2214. // of the name.
  2215. internal string ReadName ()
  2216. {
  2217. return ReadNameOrNmToken(false);
  2218. }
  2219. // The reader is positioned on the first character
  2220. // of the name.
  2221. private string ReadNmToken ()
  2222. {
  2223. return ReadNameOrNmToken(true);
  2224. }
  2225. private string ReadNameOrNmToken(bool isNameToken)
  2226. {
  2227. int ch = PeekChar ();
  2228. if(isNameToken) {
  2229. if (!XmlConstructs.IsName ((char) ch))
  2230. throw ReaderError (String.Format ("a name did not start with a legal character {0} ({1})", ch, (char)ch));
  2231. }
  2232. else {
  2233. if (!XmlConstructs.IsNameStart ((char) PeekChar ()))
  2234. throw ReaderError (String.Format ("a name did not start with a legal character {0} ({1})", ch, (char)ch));
  2235. }
  2236. nameLength = 0;
  2237. AppendNameChar (ReadChar ());
  2238. while (XmlConstructs.IsName (PeekChar ())) {
  2239. AppendNameChar (ReadChar ());
  2240. }
  2241. return CreateNameString ();
  2242. }
  2243. // Read the next character and compare it against the
  2244. // specified character.
  2245. private void Expect (int expected)
  2246. {
  2247. int ch = ReadChar ();
  2248. if (ch != expected) {
  2249. throw ReaderError (
  2250. String.Format (
  2251. "expected '{0}' ({1:X}) but found '{2}' ({3:X})",
  2252. (char)expected,
  2253. expected,
  2254. (char)ch,
  2255. ch));
  2256. }
  2257. }
  2258. private void Expect (string expected)
  2259. {
  2260. int len = expected.Length;
  2261. for(int i=0; i< len; i++)
  2262. Expect (expected[i]);
  2263. }
  2264. // Does not consume the first non-whitespace character.
  2265. private void SkipWhitespace ()
  2266. {
  2267. //FIXME: Should not skip if whitespaceHandling == WhiteSpaceHandling.None
  2268. while (XmlConstructs.IsSpace (PeekChar ()))
  2269. ReadChar ();
  2270. }
  2271. private bool ReadWhitespace ()
  2272. {
  2273. valueLength = 0;
  2274. int ch = PeekChar ();
  2275. do {
  2276. AppendValueChar (ReadChar ());
  2277. } while ((ch = PeekChar ()) != -1 && XmlConstructs.IsSpace (ch));
  2278. if (ch != -1 && ch != '<')
  2279. ReadText (false);
  2280. else
  2281. SetProperties (XmlNodeType.Whitespace,
  2282. String.Empty,
  2283. false,
  2284. CreateValueString (),
  2285. true);
  2286. return (PeekChar () != -1);
  2287. }
  2288. // read entity reference from attribute string and if parsable then return the value.
  2289. private string ReadAttributeValueReference ()
  2290. {
  2291. int endEntityPosition = attributeString.IndexOf(';',
  2292. attributeValuePos);
  2293. string entityName = attributeString.Substring (attributeValuePos + 1,
  2294. endEntityPosition - attributeValuePos - 1);
  2295. attributeValuePos = endEntityPosition + 1;
  2296. if(entityName [0] == '#') {
  2297. char c;
  2298. // character entity
  2299. if(entityName [1] == 'x') {
  2300. // hexadecimal
  2301. c = (char) int.Parse ("0" + entityName.Substring (2),
  2302. System.Globalization.NumberStyles.HexNumber);
  2303. } else {
  2304. // decimal
  2305. c = (char) int.Parse (entityName.Substring (1));
  2306. }
  2307. return c.ToString();
  2308. }
  2309. else {
  2310. switch(entityName)
  2311. {
  2312. case "lt": return "<";
  2313. case "gt": return ">";
  2314. case "amp": return "&";
  2315. case "quot": return "\"";
  2316. case "apos": return "'";
  2317. default: return null;
  2318. }
  2319. }
  2320. }
  2321. private string UnescapeAttributeValue (string unresolved)
  2322. {
  2323. if(unresolved == null) return null;
  2324. // trim start/end edge of quotation character.
  2325. return Dereference (unresolved.Substring (1, unresolved.Length - 2));
  2326. }
  2327. private string Dereference (string unresolved)
  2328. {
  2329. StringBuilder resolved = new StringBuilder();
  2330. int pos = 0;
  2331. int next = unresolved.IndexOf ('&');
  2332. if(next < 0)
  2333. return unresolved;
  2334. while(next >= 0) {
  2335. if(pos < next)
  2336. resolved.Append (unresolved.Substring (pos, next - pos));// - 1);
  2337. int endPos = unresolved.IndexOf (';', next+1);
  2338. string entityName =
  2339. unresolved.Substring (next + 1, endPos - next - 1);
  2340. if(entityName [0] == '#') {
  2341. char c;
  2342. // character entity
  2343. if(entityName [1] == 'x') {
  2344. // hexadecimal
  2345. c = (char) int.Parse ("0" + entityName.Substring (2),
  2346. System.Globalization.NumberStyles.HexNumber);
  2347. } else {
  2348. // decimal
  2349. c = (char) int.Parse (entityName.Substring (1));
  2350. }
  2351. resolved.Append (c);
  2352. } else {
  2353. switch(entityName) {
  2354. case "lt": resolved.Append ("<"); break;
  2355. case "gt": resolved.Append (">"); break;
  2356. case "amp": resolved.Append ("&"); break;
  2357. case "quot": resolved.Append ("\""); break;
  2358. case "apos": resolved.Append ("'"); break;
  2359. // With respect to "Value", MS document is helpless
  2360. // and the implemention returns inconsistent value
  2361. // (e.g. XML: "&ent; &amp;ent;" ---> Value: "&ent; &ent;".)
  2362. default: resolved.Append ("&" + entityName + ";"); break;
  2363. }
  2364. }
  2365. pos = endPos + 1;
  2366. if(pos > unresolved.Length)
  2367. break;
  2368. next = unresolved.IndexOf('&', pos);
  2369. }
  2370. resolved.Append (unresolved.Substring(pos));
  2371. return resolved.ToString();
  2372. }
  2373. #endregion
  2374. }
  2375. }