XmlTextReader.cs 64 KB

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