XmlTextReader.cs 64 KB

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