XmlTextReader.cs 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477
  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. // NameTables aren't being used completely yet.
  14. //
  15. // Some thought needs to be given to performance. There's too many
  16. // strings being allocated.
  17. //
  18. // If current node is on an Attribute, Prefix might be null, and
  19. // in several fields which uses XmlReader, it should be considered.
  20. //
  21. using System;
  22. using System.Collections;
  23. using System.Collections.Specialized;
  24. using System.IO;
  25. using System.Text;
  26. using System.Xml.Schema;
  27. using Mono.Xml;
  28. using Mono.Xml.Native;
  29. namespace System.Xml
  30. {
  31. public class XmlTextReader : XmlReader, IXmlLineInfo
  32. {
  33. #region Constructors
  34. protected XmlTextReader ()
  35. {
  36. }
  37. public XmlTextReader (Stream input)
  38. : this (new XmlStreamReader (input))
  39. {
  40. }
  41. public XmlTextReader (string url)
  42. : this(url, new NameTable ())
  43. {
  44. }
  45. public XmlTextReader (TextReader input)
  46. : this (input, new NameTable ())
  47. {
  48. }
  49. protected XmlTextReader (XmlNameTable nt)
  50. : this (String.Empty, null, XmlNodeType.None, null)
  51. {
  52. }
  53. public XmlTextReader (Stream input, XmlNameTable nt)
  54. : this(new XmlStreamReader (input), nt)
  55. {
  56. }
  57. public XmlTextReader (string url, Stream input)
  58. : this (url, new XmlStreamReader (input))
  59. {
  60. }
  61. public XmlTextReader (string url, TextReader input)
  62. : this (url, input, new NameTable ())
  63. {
  64. }
  65. public XmlTextReader (string url, XmlNameTable nt)
  66. : this (url, new XmlStreamReader (url, null, null), nt)
  67. {
  68. }
  69. public XmlTextReader (TextReader input, XmlNameTable nt)
  70. : this (String.Empty, input, nt)
  71. {
  72. }
  73. public XmlTextReader (Stream xmlFragment, XmlNodeType fragType, XmlParserContext context)
  74. : this (context != null ? context.BaseURI : String.Empty,
  75. new XmlStreamReader (xmlFragment),
  76. fragType,
  77. context)
  78. {
  79. }
  80. public XmlTextReader (string url, Stream input, XmlNameTable nt)
  81. : this (url, new XmlStreamReader (input), nt)
  82. {
  83. }
  84. public XmlTextReader (string url, TextReader input, XmlNameTable nt)
  85. : this (url, input, XmlNodeType.Document, null)
  86. {
  87. }
  88. public XmlTextReader (string xmlFragment, XmlNodeType fragType, XmlParserContext context)
  89. : this (context != null ? context.BaseURI : String.Empty,
  90. new StringReader (xmlFragment),
  91. fragType,
  92. context)
  93. {
  94. }
  95. XmlTextReader (string url, TextReader fragment, XmlNodeType fragType, XmlParserContext context)
  96. {
  97. InitializeContext (url, context, fragment, fragType);
  98. }
  99. #endregion
  100. #region Properties
  101. public override int AttributeCount
  102. {
  103. get { return attributeCount; }
  104. }
  105. public override string BaseURI
  106. {
  107. get { return parserContext.BaseURI; }
  108. }
  109. public override int Depth
  110. {
  111. get {
  112. if (currentAttributeValue >= 0)
  113. return elementDepth + 2; // inside attribute value.
  114. else if (currentAttribute >= 0)
  115. return elementDepth + 1;
  116. return elementDepth;
  117. }
  118. }
  119. public Encoding Encoding
  120. {
  121. get { return parserContext.Encoding; }
  122. }
  123. public override bool EOF
  124. {
  125. get
  126. {
  127. return
  128. readState == ReadState.EndOfFile ||
  129. readState == ReadState.Closed;
  130. }
  131. }
  132. public override bool HasValue
  133. {
  134. get {
  135. if (this.valueBuilderAvailable)
  136. return valueBuilder.Length != 0;
  137. else
  138. return cursorToken.Value != null;
  139. }
  140. }
  141. public override bool IsDefault
  142. {
  143. get
  144. {
  145. // XmlTextReader does not expand default attributes.
  146. return false;
  147. }
  148. }
  149. public override bool IsEmptyElement
  150. {
  151. get { return cursorToken.IsEmptyElement; }
  152. }
  153. public override string this [int i]
  154. {
  155. get { return GetAttribute (i); }
  156. }
  157. public override string this [string name]
  158. {
  159. get { return GetAttribute (name); }
  160. }
  161. public override string this [string localName, string namespaceName]
  162. {
  163. get { return GetAttribute (localName, namespaceName); }
  164. }
  165. public int LineNumber
  166. {
  167. get {
  168. if (useProceedingLineInfo)
  169. return line;
  170. else
  171. return cursorToken.LineNumber;
  172. }
  173. }
  174. public int LinePosition
  175. {
  176. get {
  177. if (useProceedingLineInfo)
  178. return column;
  179. else
  180. return cursorToken.LinePosition;
  181. }
  182. }
  183. public override string LocalName
  184. {
  185. get { return cursorToken.LocalName; }
  186. }
  187. public override string Name
  188. {
  189. get { return cursorToken.Name; }
  190. }
  191. public bool Namespaces
  192. {
  193. get { return namespaces; }
  194. set {
  195. if (readState != ReadState.Initial)
  196. throw new InvalidOperationException ("Namespaces have to be set before reading.");
  197. namespaces = value;
  198. }
  199. }
  200. public override string NamespaceURI
  201. {
  202. get { return cursorToken.NamespaceURI; }
  203. }
  204. public override XmlNameTable NameTable
  205. {
  206. get { return parserContext.NameTable; }
  207. }
  208. public override XmlNodeType NodeType
  209. {
  210. get { return cursorToken.NodeType; }
  211. }
  212. [MonoTODO]
  213. public bool Normalization
  214. {
  215. get { return normalization; }
  216. set { normalization = value; }
  217. }
  218. public override string Prefix
  219. {
  220. get { return cursorToken.Prefix; }
  221. }
  222. public override char QuoteChar
  223. {
  224. get { return cursorToken.QuoteChar; }
  225. }
  226. public override ReadState ReadState
  227. {
  228. get { return readState; }
  229. }
  230. public override string Value
  231. {
  232. get { return cursorToken.Value != null ? cursorToken.Value : String.Empty; }
  233. }
  234. public WhitespaceHandling WhitespaceHandling
  235. {
  236. get { return whitespaceHandling; }
  237. set { whitespaceHandling = value; }
  238. }
  239. public override string XmlLang
  240. {
  241. get { return parserContext.XmlLang; }
  242. }
  243. public XmlResolver XmlResolver
  244. {
  245. set { resolver = value; }
  246. }
  247. public override XmlSpace XmlSpace
  248. {
  249. get { return parserContext.XmlSpace; }
  250. }
  251. #endregion
  252. #region Methods
  253. public override void Close ()
  254. {
  255. readState = ReadState.Closed;
  256. cursorToken.Clear ();
  257. currentToken.Clear ();
  258. attributeCount = 0;
  259. }
  260. public override string GetAttribute (int i)
  261. {
  262. if (i > attributeCount)
  263. throw new ArgumentOutOfRangeException ("i is smaller than AttributeCount");
  264. else {
  265. return attributeTokens [i].Value;
  266. }
  267. }
  268. // MS.NET 1.0 msdn says that this method returns String.Empty
  269. // for absent attribute, but in fact it returns null.
  270. // This description is corrected in MS.NET 1.1 msdn.
  271. public override string GetAttribute (string name)
  272. {
  273. for (int i = 0; i < attributeCount; i++)
  274. if (attributeTokens [i].Name == name)
  275. return attributeTokens [i].Value;
  276. return null;
  277. }
  278. private int GetIndexOfQualifiedAttribute (string localName, string namespaceURI)
  279. {
  280. for (int i = 0; i < attributeCount; i++) {
  281. XmlAttributeTokenInfo ti = attributeTokens [i];
  282. if (ti.LocalName == localName && ti.NamespaceURI == namespaceURI)
  283. return i;
  284. }
  285. return -1;
  286. }
  287. internal XmlParserContext GetInternalParserContext ()
  288. {
  289. return parserContext;
  290. }
  291. public override string GetAttribute (string localName, string namespaceURI)
  292. {
  293. int idx = this.GetIndexOfQualifiedAttribute (localName, namespaceURI);
  294. if (idx < 0)
  295. return null;
  296. return attributeTokens [idx].Value;
  297. }
  298. public TextReader GetRemainder ()
  299. {
  300. StringBuilder sb = null;
  301. if (this.hasPeekChars) {
  302. sb = new StringBuilder ();
  303. int end = 0;
  304. for (; end < 6; end++)
  305. if (peekChars [end] <= 0)
  306. break;
  307. sb.Append (peekChars, 0, end);
  308. }
  309. if (has_peek && peek_char > 0) {
  310. if (sb != null)
  311. sb.Append ((char) peek_char);
  312. else
  313. return new StringReader (((char) peek_char) + reader.ReadToEnd ());
  314. }
  315. // As long as less memory consumptive...
  316. if (sb != null)
  317. return new StringReader (sb.ToString () + reader.ReadToEnd ());
  318. else
  319. return new StringReader (reader.ReadToEnd ());
  320. }
  321. bool IXmlLineInfo.HasLineInfo ()
  322. {
  323. return true;
  324. }
  325. public override string LookupNamespace (string prefix)
  326. {
  327. return parserContext.NamespaceManager.LookupNamespace (prefix);
  328. }
  329. public override void MoveToAttribute (int i)
  330. {
  331. if (i >= attributeCount)
  332. throw new ArgumentOutOfRangeException ("attribute index out of range.");
  333. currentAttribute = i;
  334. currentAttributeValue = -1;
  335. cursorToken = attributeTokens [i];
  336. }
  337. public override bool MoveToAttribute (string name)
  338. {
  339. for (int i = 0; i < attributeCount; i++) {
  340. XmlAttributeTokenInfo ti = attributeTokens [i];
  341. if (ti.Name == name) {
  342. MoveToAttribute (i);
  343. return true;
  344. }
  345. }
  346. return false;
  347. }
  348. public override bool MoveToAttribute (string localName, string namespaceName)
  349. {
  350. int idx = GetIndexOfQualifiedAttribute (localName, namespaceName);
  351. if (idx < 0)
  352. return false;
  353. MoveToAttribute (idx);
  354. return true;
  355. }
  356. public override bool MoveToElement ()
  357. {
  358. if (currentToken == null) // for attribute .ctor()
  359. return false;
  360. if (cursorToken == currentToken)
  361. return false;
  362. if (currentAttribute >= 0) {
  363. currentAttribute = -1;
  364. currentAttributeValue = -1;
  365. cursorToken = currentToken;
  366. return true;
  367. }
  368. else
  369. return false;
  370. }
  371. public override bool MoveToFirstAttribute ()
  372. {
  373. if (attributeCount == 0)
  374. return false;
  375. MoveToElement ();
  376. return MoveToNextAttribute ();
  377. }
  378. public override bool MoveToNextAttribute ()
  379. {
  380. if (currentAttribute == 0 && attributeCount == 0)
  381. return false;
  382. if (currentAttribute + 1 < attributeCount) {
  383. currentAttribute++;
  384. currentAttributeValue = -1;
  385. cursorToken = attributeTokens [currentAttribute];
  386. return true;
  387. }
  388. else
  389. return false;
  390. }
  391. public override bool Read ()
  392. {
  393. if (startNodeType == XmlNodeType.Attribute) {
  394. if (currentAttribute == 0)
  395. return false; // already read.
  396. ClearAttributes ();
  397. IncrementAttributeToken ();
  398. ReadAttributeValueTokens ('"');
  399. cursorToken = attributeTokens [0];
  400. currentAttributeValue = -1;
  401. readState = ReadState.Interactive;
  402. return true;
  403. }
  404. bool more = false;
  405. readState = ReadState.Interactive;
  406. currentLinkedNodeLineNumber = line;
  407. currentLinkedNodeLinePosition = column;
  408. useProceedingLineInfo = true;
  409. cursorToken = currentToken;
  410. attributeCount = 0;
  411. currentAttribute = currentAttributeValue = -1;
  412. currentToken.Clear ();
  413. // It was moved from end of ReadStartTag ().
  414. if (depthUp)
  415. ++depth;
  416. depthUp = false;
  417. if (shouldSkipUntilEndTag) {
  418. shouldSkipUntilEndTag = false;
  419. return ReadUntilEndTag ();
  420. }
  421. more = ReadContent ();
  422. if (depth == 0 && !allowMultipleRoot && (IsEmptyElement || NodeType == XmlNodeType.EndElement))
  423. currentState = XmlNodeType.EndElement;
  424. if (!more && startNodeType == XmlNodeType.Document && currentState != XmlNodeType.EndElement)
  425. throw new XmlException ("Document element did not appear.");
  426. useProceedingLineInfo = false;
  427. return more;
  428. }
  429. public override bool ReadAttributeValue ()
  430. {
  431. if (readState == ReadState.Initial && startNodeType == XmlNodeType.Attribute) {
  432. Read ();
  433. }
  434. if (currentAttribute < 0)
  435. return false;
  436. XmlAttributeTokenInfo ti = attributeTokens [currentAttribute];
  437. if (currentAttributeValue < 0)
  438. currentAttributeValue = ti.ValueTokenStartIndex - 1;
  439. if (currentAttributeValue < ti.ValueTokenEndIndex) {
  440. currentAttributeValue++;
  441. cursorToken = attributeValueTokens [currentAttributeValue];
  442. return true;
  443. }
  444. else
  445. return false;
  446. }
  447. [MonoTODO ("It looks to keep incomplete byte block.")]
  448. public int ReadBase64 (byte [] buffer, int offset, int length)
  449. {
  450. if (offset < 0)
  451. throw new ArgumentOutOfRangeException ("offset", offset, "Offset must be non-negative integer.");
  452. else if (length < 0)
  453. throw new ArgumentOutOfRangeException ("length", length, "Length must be non-negative integer.");
  454. else if (buffer.Length < offset + length)
  455. throw new ArgumentOutOfRangeException ("buffer length is smaller than the sum of offset and length.");
  456. int max = (int) System.Math.Ceiling (4.0 / 3 * length);
  457. char [] chars = new char [max];
  458. int charsLength = ReadChars (chars, 0, max);
  459. int bufIndex = offset;
  460. for (int i = 0; i < charsLength - 3; i += 4) {
  461. buffer [bufIndex] = (byte) (GetBase64Byte (chars [i]) << 2);
  462. if (i + 1 == charsLength)
  463. break;
  464. byte b = GetBase64Byte (chars [i + 1]);
  465. buffer [bufIndex] += (byte) (b >> 4);
  466. bufIndex++;
  467. buffer [bufIndex] = (byte) ((b & 0xf) << 4);
  468. if (i + 2 == charsLength)
  469. break;
  470. b = GetBase64Byte (chars [i + 2]);
  471. buffer [bufIndex] += (byte) (b >> 2);
  472. bufIndex++;
  473. buffer [bufIndex] = (byte) ((b & 3) << 6);
  474. if (i + 3 == charsLength)
  475. break;
  476. buffer [bufIndex] += GetBase64Byte (chars [i + 3]);
  477. bufIndex++;
  478. }
  479. return (int) System.Math.Ceiling (4.0 / 3 * max);
  480. }
  481. public int ReadBinHex (byte [] buffer, int offset, int length)
  482. {
  483. if (offset < 0)
  484. throw new ArgumentOutOfRangeException ("offset", offset, "Offset must be non-negative integer.");
  485. else if (length < 0)
  486. throw new ArgumentOutOfRangeException ("length", length, "Length must be non-negative integer.");
  487. else if (buffer.Length < offset + length)
  488. throw new ArgumentOutOfRangeException ("buffer length is smaller than the sum of offset and length.");
  489. char [] chars = new char [length * 2];
  490. int charsLength = ReadChars (chars, 0, length * 2);
  491. int bufIndex = offset;
  492. for (int i = 0; i < charsLength - 1; i += 2) {
  493. buffer [bufIndex] = (chars [i] > '9' ?
  494. (byte) (chars [i] - 'A' + 10) :
  495. (byte) (chars [i] - '0'));
  496. buffer [bufIndex] <<= 4;
  497. buffer [bufIndex] += chars [i + 1] > '9' ?
  498. (byte) (chars [i + 1] - 'A' + 10) :
  499. (byte) (chars [i + 1] - '0');
  500. bufIndex++;
  501. }
  502. if (charsLength %2 != 0)
  503. buffer [bufIndex++] = (byte)
  504. ((chars [charsLength - 1] > '9' ?
  505. (byte) (chars [charsLength - 1] - 'A' + 10) :
  506. (byte) (chars [charsLength - 1] - '0'))
  507. << 4);
  508. return bufIndex - offset;
  509. }
  510. public int ReadChars (char [] buffer, int offset, int length)
  511. {
  512. return ReadCharsInternal (buffer, offset, length);
  513. }
  514. #if NET_1_0
  515. public override string ReadInnerXml ()
  516. {
  517. if (readState != ReadState.Interactive)
  518. return String.Empty;
  519. switch (NodeType) {
  520. case XmlNodeType.Attribute:
  521. return value.Substring (1, value.Length - 2);
  522. case XmlNodeType.Element:
  523. if (IsEmptyElement)
  524. return String.Empty;
  525. int startDepth = depth;
  526. if (innerXmlBuilder == null)
  527. innerXmlBuilder = new StringBuilder ();
  528. innerXmlBuilder.Length = 0;
  529. bool loop = true;
  530. do {
  531. Read ();
  532. if (NodeType ==XmlNodeType.None)
  533. throw new XmlException ("unexpected end of xml.");
  534. else if (NodeType == XmlNodeType.EndElement && depth == startDepth) {
  535. loop = false;
  536. Read ();
  537. }
  538. else
  539. innerXmlBuilder.Append (currentTag);
  540. } while (loop);
  541. string xml = innerXmlBuilder.ToString ();
  542. innerXmlBuilder.Length = 0;
  543. return xml;
  544. case XmlNodeType.None:
  545. // MS document is incorrect. Seems not to progress.
  546. return String.Empty;
  547. default:
  548. Read ();
  549. return String.Empty;
  550. }
  551. }
  552. public override string ReadOuterXml ()
  553. {
  554. if (readState != ReadState.Interactive)
  555. return String.Empty;
  556. switch (NodeType) {
  557. case XmlNodeType.Attribute:
  558. // strictly incompatible with MS... (it holds spaces attribute between name, value and "=" char (very trivial).
  559. return String.Format ("{0}={1}{2}{1}", Name, QuoteChar, ReadInnerXml ());
  560. case XmlNodeType.Element:
  561. bool isEmpty = IsEmptyElement;
  562. string startTag = currentTag.ToString ();
  563. string name = Name;
  564. if (NodeType == XmlNodeType.Element && !isEmpty)
  565. return String.Format ("{0}{1}</{2}>", startTag, ReadInnerXml (), name);
  566. else
  567. return currentTag.ToString ();
  568. case XmlNodeType.None:
  569. // MS document is incorrect. Seems not to progress.
  570. return String.Empty;
  571. default:
  572. Read ();
  573. return String.Empty;
  574. }
  575. }
  576. #endif
  577. public override string ReadString ()
  578. {
  579. return ReadStringInternal ();
  580. }
  581. public void ResetState ()
  582. {
  583. Init ();
  584. }
  585. public override void ResolveEntity ()
  586. {
  587. // XmlTextReader does not resolve entities.
  588. throw new InvalidOperationException ("XmlTextReader cannot resolve external entities.");
  589. }
  590. #endregion
  591. #region Internals
  592. // Parsed DTD Objects
  593. internal DTDObjectModel DTD {
  594. get { return parserContext.Dtd; }
  595. }
  596. #endregion
  597. #region Privates
  598. internal class XmlTokenInfo
  599. {
  600. public XmlTokenInfo (XmlTextReader xtr)
  601. {
  602. Reader = xtr;
  603. Clear ();
  604. }
  605. string valueCache;
  606. protected XmlTextReader Reader;
  607. public string Name;
  608. public string LocalName;
  609. public string Prefix;
  610. public string NamespaceURI;
  611. public bool IsEmptyElement;
  612. public char QuoteChar;
  613. public int LineNumber;
  614. public int LinePosition;
  615. public XmlNodeType NodeType;
  616. public virtual string Value {
  617. get {
  618. if (valueCache != null)
  619. return valueCache;
  620. else if (Reader.valueBuilderAvailable) {
  621. valueCache = Reader.valueBuilder.ToString ();
  622. return valueCache;
  623. }
  624. return valueCache;
  625. }
  626. set {
  627. valueCache = value;
  628. }
  629. }
  630. public virtual void Clear ()
  631. {
  632. valueCache = null;
  633. NodeType = XmlNodeType.None;
  634. Name = LocalName = Prefix = NamespaceURI = String.Empty;
  635. IsEmptyElement = false;
  636. QuoteChar = '"';
  637. LineNumber = LinePosition = 0;
  638. }
  639. internal virtual void FillNames ()
  640. {
  641. if (Reader.Namespaces) {
  642. int indexOfColon = Name.IndexOf (':');
  643. if (indexOfColon == -1) {
  644. Prefix = String.Empty;
  645. LocalName = Name;
  646. } else {
  647. Prefix = Reader.NameTable.Add (Name.Substring (0, indexOfColon));
  648. LocalName = Reader.NameTable.Add (Name.Substring (indexOfColon + 1));
  649. }
  650. // NamespaceURI
  651. switch (NodeType) {
  652. case XmlNodeType.Attribute:
  653. if (Prefix == string.Empty)
  654. NamespaceURI = string.Empty;
  655. else
  656. NamespaceURI = Reader.LookupNamespace (Prefix);
  657. break;
  658. case XmlNodeType.Element:
  659. case XmlNodeType.EndElement:
  660. NamespaceURI = Reader.LookupNamespace (Prefix);
  661. break;
  662. default:
  663. NamespaceURI = "";
  664. break;
  665. }
  666. } else {
  667. Prefix = String.Empty;
  668. LocalName = Name;
  669. }
  670. }
  671. }
  672. internal class XmlAttributeTokenInfo : XmlTokenInfo
  673. {
  674. public XmlAttributeTokenInfo (XmlTextReader reader)
  675. : base (reader)
  676. {
  677. NodeType = XmlNodeType.Attribute;
  678. }
  679. public int ValueTokenStartIndex;
  680. public int ValueTokenEndIndex;
  681. string valueCache;
  682. public override string Value {
  683. get {
  684. if (valueCache != null)
  685. return valueCache;
  686. // An empty value should return String.Empty.
  687. if (ValueTokenStartIndex == ValueTokenEndIndex) {
  688. XmlTokenInfo ti = Reader.attributeValueTokens [ValueTokenStartIndex];
  689. if (ti.NodeType == XmlNodeType.Text)
  690. valueCache = ti.Value;
  691. else
  692. valueCache = String.Concat ("&", ti.Name, ";");
  693. return valueCache;
  694. }
  695. StringBuilder sb = new StringBuilder ();
  696. for (int i = ValueTokenStartIndex; i <= ValueTokenEndIndex; i++) {
  697. XmlTokenInfo ti = Reader.attributeValueTokens [i];
  698. if (ti.NodeType == XmlNodeType.Text)
  699. sb.Append (ti.Value);
  700. else {
  701. sb.Append ('&');
  702. sb.Append (ti.Name);
  703. sb.Append (';');
  704. }
  705. }
  706. valueCache = sb.ToString ();
  707. return valueCache;
  708. }
  709. set {
  710. valueCache = value;
  711. }
  712. }
  713. public override void Clear ()
  714. {
  715. base.Clear ();
  716. valueCache = null;
  717. NodeType = XmlNodeType.Attribute;
  718. ValueTokenStartIndex = ValueTokenEndIndex = 0;
  719. }
  720. internal override void FillNames ()
  721. {
  722. base.FillNames ();
  723. if (Prefix == "xmlns" || Name == "xmlns")
  724. NamespaceURI = XmlNamespaceManager.XmlnsXmlns;
  725. }
  726. }
  727. private XmlTokenInfo cursorToken;
  728. private XmlTokenInfo currentToken;
  729. private XmlAttributeTokenInfo currentAttributeToken;
  730. private XmlTokenInfo currentAttributeValueToken;
  731. private XmlAttributeTokenInfo [] attributeTokens = new XmlAttributeTokenInfo [10];
  732. private XmlTokenInfo [] attributeValueTokens = new XmlTokenInfo [10];
  733. private int currentAttribute;
  734. private int currentAttributeValue;
  735. private int attributeCount;
  736. private XmlParserContext parserContext;
  737. private ReadState readState;
  738. private int depth;
  739. private int elementDepth;
  740. private bool depthUp;
  741. private bool popScope;
  742. private Stack elementStack;
  743. private bool allowMultipleRoot;
  744. private bool isStandalone;
  745. private StringBuilder valueBuilder;
  746. private bool valueBuilderAvailable = false;
  747. private bool returnEntityReference;
  748. private string entityReferenceName;
  749. private char [] nameBuffer;
  750. private int nameLength;
  751. private int nameCapacity;
  752. private const int initialNameCapacity = 256;
  753. private StringBuilder valueBuffer;
  754. private TextReader reader;
  755. private bool can_seek;
  756. private bool has_peek;
  757. private int peek_char;
  758. private bool hasPeekChars;
  759. private char [] peekChars;
  760. private int peekCharsIndex;
  761. private int line;
  762. private int column;
  763. private StringBuilder currentTag;
  764. private int currentLinkedNodeLineNumber;
  765. private int currentLinkedNodeLinePosition;
  766. private bool useProceedingLineInfo;
  767. // A buffer for ReadContent for ReadOuterXml
  768. private XmlNodeType startNodeType;
  769. // State machine attribute.
  770. // XmlDeclaration: after the first node.
  771. // DocumentType: after doctypedecl
  772. // Element: inside document element
  773. // EndElement: after document element
  774. private XmlNodeType currentState;
  775. private XmlResolver resolver = new XmlUrlResolver ();
  776. // These values are never re-initialized.
  777. private bool namespaces = true;
  778. private WhitespaceHandling whitespaceHandling = WhitespaceHandling.All;
  779. private bool normalization = false;
  780. // For ReadChars()/ReadBase64()/ReadBinHex()
  781. private bool shouldSkipUntilEndTag;
  782. private void Init ()
  783. {
  784. readState = ReadState.Initial;
  785. currentState = XmlNodeType.None;
  786. allowMultipleRoot = false;
  787. depth = 0;
  788. depthUp = false;
  789. currentTag = new StringBuilder ();
  790. peek_char = 0;
  791. has_peek = false;
  792. can_seek = false;
  793. hasPeekChars = false;
  794. peekChars = new char [6];
  795. popScope = false;
  796. elementStack = new Stack();
  797. currentAttribute = -1;
  798. currentAttributeValue = -1;
  799. returnEntityReference = false;
  800. entityReferenceName = String.Empty;
  801. nameBuffer = new char [initialNameCapacity];
  802. nameLength = 0;
  803. nameCapacity = initialNameCapacity;
  804. valueBuffer = new StringBuilder (512);
  805. currentToken = new XmlTokenInfo (this);
  806. cursorToken = currentToken;
  807. }
  808. private void InitializeContext (string url, XmlParserContext context, TextReader fragment, XmlNodeType fragType)
  809. {
  810. startNodeType = fragType;
  811. parserContext = context;
  812. if (context == null) {
  813. XmlNameTable nt = new NameTable ();
  814. parserContext = new XmlParserContext (nt,
  815. new XmlNamespaceManager (nt),
  816. String.Empty,
  817. XmlSpace.None);
  818. }
  819. if (url != null && url != String.Empty) {
  820. string path = Path.GetFullPath ("./a");
  821. Uri uri = new Uri (new Uri (path), url);
  822. parserContext.BaseURI = uri.ToString ();
  823. }
  824. Init ();
  825. switch (fragType) {
  826. case XmlNodeType.Attribute:
  827. fragment = new StringReader (fragment.ReadToEnd ().Replace ("\"", "&quot;"));
  828. break;
  829. case XmlNodeType.Element:
  830. currentState = XmlNodeType.Element;
  831. allowMultipleRoot = true;
  832. break;
  833. case XmlNodeType.Document:
  834. break;
  835. default:
  836. throw new XmlException (String.Format ("NodeType {0} is not allowed to create XmlTextReader.", fragType));
  837. }
  838. reader = fragment;
  839. }
  840. // Use this method rather than setting the properties
  841. // directly so that all the necessary properties can
  842. // be changed in harmony with each other. Maybe the
  843. // fields should be in a seperate class to help enforce
  844. // this.
  845. private void SetProperties (
  846. XmlNodeType nodeType,
  847. string name,
  848. bool isEmptyElement,
  849. string value,
  850. bool clearAttributes)
  851. {
  852. SetProperties (currentToken, nodeType, name, isEmptyElement, value, clearAttributes);
  853. currentToken.LineNumber = this.currentLinkedNodeLineNumber;
  854. currentToken.LinePosition = this.currentLinkedNodeLinePosition;
  855. }
  856. private void SetProperties (
  857. XmlTokenInfo token,
  858. XmlNodeType nodeType,
  859. string name,
  860. bool isEmptyElement,
  861. string value,
  862. bool clearAttributes)
  863. {
  864. this.valueBuilderAvailable = false;
  865. token.Clear ();
  866. token.NodeType = nodeType;
  867. token.Name = name;
  868. token.IsEmptyElement = isEmptyElement;
  869. token.Value = value;
  870. this.elementDepth = depth;
  871. if (clearAttributes)
  872. ClearAttributes ();
  873. token.FillNames ();
  874. }
  875. private void SetProperties (
  876. XmlNodeType nodeType,
  877. string name,
  878. bool isEmptyElement,
  879. bool clearAttributes,
  880. StringBuilder value) {
  881. SetProperties (nodeType, name, isEmptyElement, (string)null, clearAttributes);
  882. this.valueBuilderAvailable = true;
  883. this.valueBuilder = value;
  884. }
  885. private void ClearAttributes ()
  886. {
  887. for (int i = 0; i < attributeCount; i++)
  888. attributeTokens [i].Clear ();
  889. attributeCount = 0;
  890. currentAttribute = -1;
  891. currentAttributeValue = -1;
  892. }
  893. /*
  894. private int PeekChar ()
  895. {
  896. return currentInput.PeekChar ();
  897. }
  898. private int ReadChar ()
  899. {
  900. return currentInput.ReadChar ();
  901. }
  902. */
  903. public int PeekChar ()
  904. {
  905. if (can_seek)
  906. return reader.Peek ();
  907. if (hasPeekChars)
  908. return peekChars [peekCharsIndex];
  909. if (has_peek)
  910. return peek_char;
  911. peek_char = reader.Read ();
  912. has_peek = true;
  913. return peek_char;
  914. }
  915. public int ReadChar ()
  916. {
  917. int ch;
  918. if (hasPeekChars) {
  919. ch = peekChars [peekCharsIndex++];
  920. if (peekChars [peekCharsIndex] == 0)
  921. hasPeekChars = false;
  922. } else if (has_peek) {
  923. ch = peek_char;
  924. has_peek = false;
  925. } else {
  926. ch = reader.Read ();
  927. }
  928. if (ch == '\n') {
  929. line++;
  930. column = 1;
  931. } else {
  932. column++;
  933. }
  934. currentTag.Append ((char) ch);
  935. return ch;
  936. }
  937. // This should really keep track of some state so
  938. // that it's not possible to have more than one document
  939. // element or text outside of the document element.
  940. private bool ReadContent ()
  941. {
  942. currentTag.Length = 0;
  943. if (popScope) {
  944. parserContext.NamespaceManager.PopScope ();
  945. popScope = false;
  946. }
  947. if (returnEntityReference)
  948. SetEntityReferenceProperties ();
  949. else {
  950. switch (PeekChar ()) {
  951. case '<':
  952. ReadChar ();
  953. ReadTag ();
  954. break;
  955. case '\r': goto case ' ';
  956. case '\n': goto case ' ';
  957. case '\t': goto case ' ';
  958. case ' ':
  959. if (whitespaceHandling == WhitespaceHandling.All ||
  960. whitespaceHandling == WhitespaceHandling.Significant)
  961. ReadWhitespace ();
  962. else {
  963. SkipWhitespace ();
  964. return ReadContent ();
  965. }
  966. break;
  967. case -1:
  968. readState = ReadState.EndOfFile;
  969. SetProperties (
  970. XmlNodeType.None, // nodeType
  971. String.Empty, // name
  972. false, // isEmptyElement
  973. (string) null, // value
  974. true // clearAttributes
  975. );
  976. if (depth > 0)
  977. throw new XmlException ("unexpected end of file. Current depth is " + depth);
  978. return false;
  979. default:
  980. ReadText (true);
  981. break;
  982. }
  983. }
  984. return this.ReadState != ReadState.EndOfFile;
  985. }
  986. private void SetEntityReferenceProperties ()
  987. {
  988. DTDEntityDeclaration decl = DTD != null ? DTD.EntityDecls [entityReferenceName] : null;
  989. // if (DTD != null && resolver != null && decl == null)
  990. // throw new XmlException (this as IXmlLineInfo, "Entity declaration does not exist.");
  991. if (this.isStandalone)
  992. if (DTD == null || decl == null || !decl.IsInternalSubset)
  993. throw new XmlException (this as IXmlLineInfo,
  994. "Standalone document must not contain any references to an non-internally declared entity.");
  995. if (decl != null && decl.NotationName != null)
  996. throw new XmlException (this as IXmlLineInfo,
  997. "Reference to any unparsed entities is not allowed here.");
  998. SetProperties (
  999. XmlNodeType.EntityReference, // nodeType
  1000. entityReferenceName, // name
  1001. false, // isEmptyElement
  1002. (string) null, // value
  1003. true // clearAttributes
  1004. );
  1005. returnEntityReference = false;
  1006. entityReferenceName = String.Empty;
  1007. }
  1008. // The leading '<' has already been consumed.
  1009. private void ReadTag ()
  1010. {
  1011. switch (PeekChar ())
  1012. {
  1013. case '/':
  1014. ReadChar ();
  1015. ReadEndTag ();
  1016. break;
  1017. case '?':
  1018. ReadChar ();
  1019. ReadProcessingInstruction ();
  1020. break;
  1021. case '!':
  1022. ReadChar ();
  1023. ReadDeclaration ();
  1024. break;
  1025. default:
  1026. ReadStartTag ();
  1027. break;
  1028. }
  1029. }
  1030. // The leading '<' has already been consumed.
  1031. private void ReadStartTag ()
  1032. {
  1033. if (currentState == XmlNodeType.EndElement)
  1034. throw new XmlException (this as IXmlLineInfo,
  1035. "Element cannot appear in this state.");
  1036. currentState = XmlNodeType.Element;
  1037. parserContext.NamespaceManager.PushScope ();
  1038. string name = ReadName ();
  1039. if (currentState == XmlNodeType.EndElement)
  1040. throw new XmlException (this as IXmlLineInfo,"document has terminated, cannot open new element");
  1041. bool isEmptyElement = false;
  1042. ClearAttributes ();
  1043. SkipWhitespace ();
  1044. if (XmlChar.IsFirstNameChar (PeekChar ()))
  1045. ReadAttributes (false);
  1046. cursorToken = this.currentToken;
  1047. // fill namespaces
  1048. for (int i = 0; i < attributeCount; i++)
  1049. attributeTokens [i].FillNames ();
  1050. // quick name check
  1051. for (int i = 0; i < attributeCount; i++)
  1052. for (int j = i + 1; j < attributeCount; j++)
  1053. if (Object.ReferenceEquals (attributeTokens [i].Name, attributeTokens [j].Name) ||
  1054. (Object.ReferenceEquals (attributeTokens [i].LocalName, attributeTokens [j].LocalName) &&
  1055. Object.ReferenceEquals (attributeTokens [i].NamespaceURI, attributeTokens [j].NamespaceURI)))
  1056. throw new XmlException (this as IXmlLineInfo,
  1057. "Attribute name and qualified name must be identical.");
  1058. string baseUri = GetAttribute ("xml:base");
  1059. if (baseUri != null)
  1060. parserContext.BaseURI = baseUri;
  1061. string xmlLang = GetAttribute ("xml:lang");
  1062. if (xmlLang != null)
  1063. parserContext.XmlLang = xmlLang;
  1064. string xmlSpaceAttr = GetAttribute ("xml:space");
  1065. if (xmlSpaceAttr != null) {
  1066. if (xmlSpaceAttr == "preserve")
  1067. parserContext.XmlSpace = XmlSpace.Preserve;
  1068. else if (xmlSpaceAttr == "default")
  1069. parserContext.XmlSpace = XmlSpace.Default;
  1070. else
  1071. throw new XmlException (this as IXmlLineInfo,String.Format ("Invalid xml:space value: {0}", xmlSpaceAttr));
  1072. }
  1073. if (PeekChar () == '/') {
  1074. ReadChar ();
  1075. isEmptyElement = true;
  1076. popScope = true;
  1077. }
  1078. else {
  1079. depthUp = true;
  1080. elementStack.Push (name);
  1081. parserContext.PushScope ();
  1082. }
  1083. Expect ('>');
  1084. SetProperties (
  1085. XmlNodeType.Element, // nodeType
  1086. name, // name
  1087. isEmptyElement, // isEmptyElement
  1088. (string) null, // value
  1089. false // clearAttributes
  1090. );
  1091. }
  1092. // The reader is positioned on the first character
  1093. // of the element's name.
  1094. private void ReadEndTag ()
  1095. {
  1096. if (currentState != XmlNodeType.Element)
  1097. throw new XmlException (this as IXmlLineInfo,
  1098. "End tag cannot appear in this state.");
  1099. string name = ReadName ();
  1100. if (elementStack.Count == 0)
  1101. throw new XmlException (this as IXmlLineInfo,"closing element without matching opening element");
  1102. string expected = (string)elementStack.Pop();
  1103. if (expected != name)
  1104. throw new XmlException (this as IXmlLineInfo,String.Format ("unmatched closing element: expected {0} but found {1}", expected, name));
  1105. parserContext.PopScope ();
  1106. SkipWhitespace ();
  1107. Expect ('>');
  1108. --depth;
  1109. SetProperties (
  1110. XmlNodeType.EndElement, // nodeType
  1111. name, // name
  1112. false, // isEmptyElement
  1113. (string) null, // value
  1114. true // clearAttributes
  1115. );
  1116. popScope = true;
  1117. }
  1118. private void AppendNameChar (int ch)
  1119. {
  1120. CheckNameCapacity ();
  1121. nameBuffer [nameLength++] = (char)ch;
  1122. }
  1123. private void CheckNameCapacity ()
  1124. {
  1125. if (nameLength == nameCapacity) {
  1126. nameCapacity = nameCapacity * 2;
  1127. char [] oldNameBuffer = nameBuffer;
  1128. nameBuffer = new char [nameCapacity];
  1129. Array.Copy (oldNameBuffer, nameBuffer, nameLength);
  1130. }
  1131. }
  1132. private string CreateNameString ()
  1133. {
  1134. return parserContext.NameTable.Add (nameBuffer, 0, nameLength);
  1135. }
  1136. private void AppendValueChar (int ch)
  1137. {
  1138. valueBuffer.Append ((char)ch);
  1139. }
  1140. private string CreateValueString ()
  1141. {
  1142. return valueBuffer.ToString ();
  1143. }
  1144. private void ClearValueBuffer ()
  1145. {
  1146. valueBuffer.Length = 0;
  1147. }
  1148. // The reader is positioned on the first character
  1149. // of the text.
  1150. private void ReadText (bool notWhitespace)
  1151. {
  1152. if (currentState != XmlNodeType.Element)
  1153. throw new XmlException (this as IXmlLineInfo,
  1154. "Text node cannot appear in this state.");
  1155. if (notWhitespace)
  1156. ClearValueBuffer ();
  1157. int ch = PeekChar ();
  1158. int previousCloseBracketLine = 0;
  1159. int previousCloseBracketColumn = 0;
  1160. while (ch != '<' && ch != -1) {
  1161. if (ch == '&') {
  1162. ReadChar ();
  1163. if (ReadReference (false))
  1164. break;
  1165. } else {
  1166. if (XmlConstructs.IsInvalid (ch))
  1167. throw new XmlException (this as IXmlLineInfo,
  1168. "Not allowed character was found.");
  1169. AppendValueChar (ReadChar ());
  1170. if (ch == ']') {
  1171. if (previousCloseBracketColumn == LinePosition - 1 &&
  1172. previousCloseBracketLine == LineNumber)
  1173. if (PeekChar () == '>')
  1174. throw new XmlException (this as IXmlLineInfo,
  1175. "Inside text content, character sequence ']]>' is not allowed.");
  1176. previousCloseBracketColumn = LinePosition;
  1177. previousCloseBracketLine = LineNumber;
  1178. }
  1179. }
  1180. ch = PeekChar ();
  1181. notWhitespace = true;
  1182. }
  1183. if (returnEntityReference && valueBuffer.Length == 0) {
  1184. SetEntityReferenceProperties ();
  1185. } else {
  1186. XmlNodeType nodeType = notWhitespace ? XmlNodeType.Text :
  1187. this.XmlSpace == XmlSpace.Preserve ? XmlNodeType.SignificantWhitespace : XmlNodeType.Whitespace;
  1188. SetProperties (
  1189. nodeType, // nodeType
  1190. String.Empty, // name
  1191. false, // isEmptyElement
  1192. true, // clearAttributes
  1193. valueBuffer // value
  1194. );
  1195. }
  1196. }
  1197. // The leading '&' has already been consumed.
  1198. // Returns true if the entity reference isn't a simple
  1199. // character reference or one of the predefined entities.
  1200. // This allows the ReadText method to break so that the
  1201. // next call to Read will return the EntityReference node.
  1202. private bool ReadReference (bool ignoreEntityReferences)
  1203. {
  1204. if (PeekChar () == '#') {
  1205. ReadChar ();
  1206. ReadCharacterReference ();
  1207. } else
  1208. ReadEntityReference (ignoreEntityReferences);
  1209. return returnEntityReference;
  1210. }
  1211. private void ReadCharacterReference ()
  1212. {
  1213. int value = 0;
  1214. if (PeekChar () == 'x') {
  1215. ReadChar ();
  1216. while (PeekChar () != ';' && PeekChar () != -1) {
  1217. int ch = ReadChar ();
  1218. if (ch >= '0' && ch <= '9')
  1219. value = (value << 4) + ch - '0';
  1220. else if (ch >= 'A' && ch <= 'F')
  1221. value = (value << 4) + ch - 'A' + 10;
  1222. else if (ch >= 'a' && ch <= 'f')
  1223. value = (value << 4) + ch - 'a' + 10;
  1224. else
  1225. throw new XmlException (this as IXmlLineInfo,
  1226. String.Format (
  1227. "invalid hexadecimal digit: {0} (#x{1:X})",
  1228. (char)ch,
  1229. ch));
  1230. }
  1231. } else {
  1232. while (PeekChar () != ';' && PeekChar () != -1) {
  1233. int ch = ReadChar ();
  1234. if (ch >= '0' && ch <= '9')
  1235. value = value * 10 + ch - '0';
  1236. else
  1237. throw new XmlException (this as IXmlLineInfo,
  1238. String.Format (
  1239. "invalid decimal digit: {0} (#x{1:X})",
  1240. (char)ch,
  1241. ch));
  1242. }
  1243. }
  1244. ReadChar (); // ';'
  1245. // FIXME: how to handle such chars larger than 0xffff?
  1246. if (value < 0xffff && !XmlConstructs.IsValid (value))
  1247. throw new XmlException (this as IXmlLineInfo,
  1248. "Referenced character was not allowed in XML.");
  1249. AppendValueChar (value);
  1250. }
  1251. private void ReadEntityReference (bool ignoreEntityReferences)
  1252. {
  1253. nameLength = 0;
  1254. int ch = PeekChar ();
  1255. while (ch != ';' && ch != -1) {
  1256. AppendNameChar (ReadChar ());
  1257. ch = PeekChar ();
  1258. }
  1259. Expect (';');
  1260. string name = CreateNameString ();
  1261. if (!XmlChar.IsName (name))
  1262. throw new XmlException (this as IXmlLineInfo,
  1263. "Invalid entity reference name was found.");
  1264. char predefined = XmlChar.GetPredefinedEntity (name);
  1265. if (predefined != 0)
  1266. AppendValueChar (predefined);
  1267. else {
  1268. if (ignoreEntityReferences) {
  1269. AppendValueChar ('&');
  1270. foreach (char ch2 in name) {
  1271. AppendValueChar (ch2);
  1272. }
  1273. AppendValueChar (';');
  1274. } else {
  1275. returnEntityReference = true;
  1276. entityReferenceName = name;
  1277. }
  1278. }
  1279. }
  1280. // The reader is positioned on the first character of
  1281. // the attribute name.
  1282. private void ReadAttributes (bool endsWithQuestion)
  1283. {
  1284. int peekChar = -1;
  1285. bool requireWhitespace = false;
  1286. currentAttribute = -1;
  1287. currentAttributeValue = -1;
  1288. do {
  1289. if (!SkipWhitespace () && requireWhitespace)
  1290. throw new XmlException ("Unexpected token. Name is required here.");
  1291. IncrementAttributeToken ();
  1292. currentAttributeToken.LineNumber = line;
  1293. currentAttributeToken.LinePosition = column;
  1294. currentAttributeToken.Name = ReadName ();
  1295. SkipWhitespace ();
  1296. Expect ('=');
  1297. SkipWhitespace ();
  1298. ReadAttributeValueTokens (-1);
  1299. attributeCount++;
  1300. if (currentAttributeToken.Name == "xmlns")
  1301. parserContext.NamespaceManager.AddNamespace (String.Empty, GetAttribute (currentAttribute));
  1302. else if (currentAttributeToken.Name.StartsWith ("xmlns:")) {
  1303. string nsPrefix = NameTable.Add (currentAttributeToken.Name.Substring (6));
  1304. parserContext.NamespaceManager.AddNamespace (nsPrefix, GetAttribute (currentAttribute));
  1305. }
  1306. if (!SkipWhitespace ())
  1307. requireWhitespace = true;
  1308. peekChar = PeekChar ();
  1309. if (endsWithQuestion) {
  1310. if (peekChar == '?')
  1311. break;
  1312. }
  1313. else if (peekChar == '/' || peekChar == '>')
  1314. break;
  1315. } while (peekChar != -1);
  1316. currentAttribute = -1;
  1317. currentAttributeValue = -1;
  1318. }
  1319. private void AddAttribute (string name, string value)
  1320. {
  1321. IncrementAttributeToken ();
  1322. XmlAttributeTokenInfo ati = attributeTokens [currentAttribute];
  1323. ati.Name = "SYSTEM";
  1324. ati.FillNames ();
  1325. IncrementAttributeValueToken ();
  1326. XmlTokenInfo vti = attributeValueTokens [currentAttributeValue];
  1327. vti.Value = value;
  1328. SetProperties (vti, XmlNodeType.Text, name, false, value, false);
  1329. attributeCount++;
  1330. }
  1331. private void IncrementAttributeToken ()
  1332. {
  1333. currentAttribute++;
  1334. if (attributeTokens.Length == currentAttribute) {
  1335. XmlAttributeTokenInfo [] newArray =
  1336. new XmlAttributeTokenInfo [attributeTokens.Length * 2];
  1337. attributeTokens.CopyTo (newArray, 0);
  1338. attributeTokens = newArray;
  1339. }
  1340. if (attributeTokens [currentAttribute] == null)
  1341. attributeTokens [currentAttribute] = new XmlAttributeTokenInfo (this);
  1342. currentAttributeToken = attributeTokens [currentAttribute];
  1343. currentAttributeToken.Clear ();
  1344. }
  1345. private void IncrementAttributeValueToken ()
  1346. {
  1347. ClearValueBuffer ();
  1348. currentAttributeValue++;
  1349. if (attributeValueTokens.Length == currentAttributeValue) {
  1350. XmlTokenInfo [] newArray = new XmlTokenInfo [attributeValueTokens.Length * 2];
  1351. attributeValueTokens.CopyTo (newArray, 0);
  1352. attributeValueTokens = newArray;
  1353. }
  1354. if (attributeValueTokens [currentAttributeValue] == null)
  1355. attributeValueTokens [currentAttributeValue] = new XmlTokenInfo (this);
  1356. currentAttributeValueToken = attributeValueTokens [currentAttributeValue];
  1357. currentAttributeValueToken.Clear ();
  1358. }
  1359. private void ReadAttributeValueTokens (int dummyQuoteChar)
  1360. {
  1361. int quoteChar = (dummyQuoteChar < 0) ? ReadChar () : dummyQuoteChar;
  1362. if (quoteChar != '\'' && quoteChar != '\"')
  1363. throw new XmlException (this as IXmlLineInfo,"an attribute value was not quoted");
  1364. currentAttributeToken.QuoteChar = (char) quoteChar;
  1365. IncrementAttributeValueToken ();
  1366. currentAttributeToken.ValueTokenStartIndex = currentAttributeValue;
  1367. currentAttributeValueToken.LineNumber = line;
  1368. currentAttributeValueToken.LinePosition = column;
  1369. bool incrementToken = false;
  1370. bool isNewToken = true;
  1371. bool loop = true;
  1372. while (loop && PeekChar () != quoteChar) {
  1373. if (incrementToken) {
  1374. IncrementAttributeValueToken ();
  1375. currentAttributeValueToken.LineNumber = line;
  1376. currentAttributeValueToken.LinePosition = column;
  1377. incrementToken = false;
  1378. isNewToken = true;
  1379. }
  1380. int ch = ReadChar ();
  1381. switch (ch)
  1382. {
  1383. case '<':
  1384. throw new XmlException (this as IXmlLineInfo,"attribute values cannot contain '<'");
  1385. case -1:
  1386. if (dummyQuoteChar < 0)
  1387. throw new XmlException (this as IXmlLineInfo,"unexpected end of file in an attribute value");
  1388. else // Attribute value constructor.
  1389. loop = false;
  1390. break;
  1391. case '&':
  1392. int startPosition = currentTag.Length - 1;
  1393. if (PeekChar () == '#') {
  1394. ReadChar ();
  1395. this.ReadCharacterReference ();
  1396. break;
  1397. }
  1398. // Check XML 1.0 section 3.1 WFC.
  1399. string entName = ReadName ();
  1400. Expect (';');
  1401. int predefined = XmlChar.GetPredefinedEntity (entName);
  1402. if (predefined == 0) {
  1403. DTDEntityDeclaration entDecl =
  1404. DTD == null ? null : DTD.EntityDecls [entName];
  1405. if (DTD != null && resolver != null && entDecl == null)
  1406. throw new XmlException (this as IXmlLineInfo, "Entity declaration does not exist.");
  1407. if (entDecl != null && entDecl.HasExternalReference)
  1408. throw new XmlException (this as IXmlLineInfo,
  1409. "Reference to external entities is not allowed in the value of an attribute.");
  1410. if (isStandalone && !entDecl.IsInternalSubset)
  1411. throw new XmlException (this as IXmlLineInfo,
  1412. "Reference to external entities is not allowed in the value of an attribute.");
  1413. if (entDecl != null && entDecl.EntityValue.IndexOf ('<') >= 0)
  1414. throw new XmlException (this as IXmlLineInfo,
  1415. "Attribute must not contain character '<' either directly or indirectly by way of entity references.");
  1416. currentAttributeValueToken.Value = CreateValueString ();
  1417. currentAttributeValueToken.NodeType = XmlNodeType.Text;
  1418. if (!isNewToken)
  1419. IncrementAttributeValueToken ();
  1420. currentAttributeValueToken.Name = entName;
  1421. currentAttributeValueToken.Value = String.Empty;
  1422. currentAttributeValueToken.NodeType = XmlNodeType.EntityReference;
  1423. incrementToken = true;
  1424. }
  1425. else
  1426. AppendValueChar (predefined);
  1427. break;
  1428. default:
  1429. AppendValueChar (ch);
  1430. break;
  1431. }
  1432. isNewToken = false;
  1433. }
  1434. if (!incrementToken) {
  1435. currentAttributeValueToken.Value = CreateValueString ();
  1436. currentAttributeValueToken.NodeType = XmlNodeType.Text;
  1437. }
  1438. currentAttributeToken.ValueTokenEndIndex = currentAttributeValue;
  1439. if (dummyQuoteChar < 0)
  1440. ReadChar (); // quoteChar
  1441. }
  1442. // The reader is positioned on the first character
  1443. // of the target.
  1444. //
  1445. // It may be xml declaration or processing instruction.
  1446. private void ReadProcessingInstruction ()
  1447. {
  1448. string target = ReadName ();
  1449. if (target == "xml") {
  1450. ReadXmlDeclaration ();
  1451. return;
  1452. } else if (target.ToLower () == "xml")
  1453. throw new XmlException (this as IXmlLineInfo,
  1454. "Not allowed processing instruction name which starts with 'X', 'M', 'L' was found.");
  1455. if (currentState == XmlNodeType.None)
  1456. currentState = XmlNodeType.XmlDeclaration;
  1457. if (!SkipWhitespace ())
  1458. if (PeekChar () != '?')
  1459. throw new XmlException (this as IXmlLineInfo,
  1460. "Invalid processing instruction name was found.");
  1461. ClearValueBuffer ();
  1462. while (PeekChar () != -1) {
  1463. int ch = ReadChar ();
  1464. if (ch == '?' && PeekChar () == '>') {
  1465. ReadChar ();
  1466. break;
  1467. }
  1468. AppendValueChar ((char)ch);
  1469. }
  1470. SetProperties (
  1471. XmlNodeType.ProcessingInstruction, // nodeType
  1472. target, // name
  1473. false, // isEmptyElement
  1474. true, // clearAttributes
  1475. valueBuffer // value
  1476. );
  1477. }
  1478. // The reader is positioned after "<?xml "
  1479. private void ReadXmlDeclaration ()
  1480. {
  1481. if (currentState != XmlNodeType.None) {
  1482. throw new XmlException (this as IXmlLineInfo,
  1483. "XML declaration cannot appear in this state.");
  1484. }
  1485. currentState = XmlNodeType.XmlDeclaration;
  1486. ClearAttributes ();
  1487. ReadAttributes (true); // They must have "version."
  1488. string version = GetAttribute ("version");
  1489. string message = null;
  1490. if (attributeTokens [0].Name != "version" || version != "1.0")
  1491. message = "Version 1.0 declaration is required in XML Declaration.";
  1492. else if (attributeCount > 1 &&
  1493. (attributeTokens [1].Name != "encoding" &&
  1494. attributeTokens [1].Name != "standalone"))
  1495. message = "Invalid Xml Declaration markup was found.";
  1496. else if (attributeCount > 2 && attributeTokens [2].Name != "standalone")
  1497. message = "Invalid Xml Declaration markup was found.";
  1498. string sa = GetAttribute ("standalone");
  1499. if (sa != null && sa != "yes" && sa != "no")
  1500. message = "Only 'yes' or 'no' is allowed for standalone.";
  1501. this.isStandalone = (sa == "yes");
  1502. if (message != null)
  1503. throw new XmlException (this as IXmlLineInfo, message);
  1504. SetProperties (
  1505. XmlNodeType.XmlDeclaration, // nodeType
  1506. "xml", // name
  1507. false, // isEmptyElement
  1508. currentTag.ToString (6, currentTag.Length - 6), // value
  1509. false // clearAttributes
  1510. );
  1511. Expect ("?>");
  1512. }
  1513. internal void SkipTextDeclaration ()
  1514. {
  1515. this.currentState = XmlNodeType.Element;
  1516. if (PeekChar () != '<')
  1517. return;
  1518. ReadChar ();
  1519. peekChars [0] = '<';
  1520. if (PeekChar () != '?') {
  1521. hasPeekChars = true;
  1522. return;
  1523. }
  1524. ReadChar ();
  1525. peekChars [1] = '?';
  1526. for (int i = 2; i < 6; i++) {
  1527. if (PeekChar () == 0)
  1528. break;
  1529. else
  1530. peekChars [i] = (char) ReadChar ();
  1531. }
  1532. if (new string (peekChars, 2, 4) != "xml ") {
  1533. if (new string (peekChars, 2, 3).ToLower () == "xml") {
  1534. throw new XmlException (this as IXmlLineInfo,
  1535. "Processing instruction name must not be character sequence 'X' 'M' 'L' with case insensitivity.");
  1536. }
  1537. hasPeekChars = true;
  1538. return;
  1539. }
  1540. for (int i = 0; i < 6; i++)
  1541. peekChars [i] = '\0';
  1542. SkipWhitespace ();
  1543. // version decl
  1544. if (PeekChar () == 'v') {
  1545. Expect ("version");
  1546. SkipWhitespace ();
  1547. Expect ('=');
  1548. SkipWhitespace ();
  1549. int quoteChar = ReadChar ();
  1550. char [] expect1_0 = new char [3];
  1551. int versionLength = 0;
  1552. switch (quoteChar) {
  1553. case '\'':
  1554. case '"':
  1555. while (PeekChar () != quoteChar) {
  1556. if (PeekChar () == -1)
  1557. throw new XmlException (this as IXmlLineInfo,
  1558. "Invalid version declaration inside text declaration.");
  1559. else if (versionLength == 3)
  1560. throw new XmlException (this as IXmlLineInfo,
  1561. "Invalid version number inside text declaration.");
  1562. else {
  1563. expect1_0 [versionLength] = (char) ReadChar ();
  1564. versionLength++;
  1565. if (versionLength == 3 && new String (expect1_0) != "1.0")
  1566. throw new XmlException (this as IXmlLineInfo,
  1567. "Invalid version number inside text declaration.");
  1568. }
  1569. }
  1570. ReadChar ();
  1571. SkipWhitespace ();
  1572. break;
  1573. default:
  1574. throw new XmlException (this as IXmlLineInfo,
  1575. "Invalid version declaration inside text declaration.");
  1576. }
  1577. }
  1578. if (PeekChar () == 'e') {
  1579. Expect ("encoding");
  1580. SkipWhitespace ();
  1581. Expect ('=');
  1582. SkipWhitespace ();
  1583. int quoteChar = ReadChar ();
  1584. switch (quoteChar) {
  1585. case '\'':
  1586. case '"':
  1587. while (PeekChar () != quoteChar)
  1588. if (ReadChar () == -1)
  1589. throw new XmlException (this as IXmlLineInfo,
  1590. "Invalid encoding declaration inside text declaration.");
  1591. ReadChar ();
  1592. SkipWhitespace ();
  1593. break;
  1594. default:
  1595. throw new XmlException (this as IXmlLineInfo,
  1596. "Invalid encoding declaration inside text declaration.");
  1597. }
  1598. // Encoding value should be checked inside XmlInputStream.
  1599. }
  1600. else
  1601. throw new XmlException (this as IXmlLineInfo,
  1602. "Encoding declaration is mandatory in text declaration.");
  1603. Expect ("?>");
  1604. }
  1605. // The reader is positioned on the first character after
  1606. // the leading '<!'.
  1607. private void ReadDeclaration ()
  1608. {
  1609. int ch = PeekChar ();
  1610. switch (ch)
  1611. {
  1612. case '-':
  1613. Expect ("--");
  1614. ReadComment ();
  1615. break;
  1616. case '[':
  1617. ReadChar ();
  1618. Expect ("CDATA[");
  1619. ReadCDATA ();
  1620. break;
  1621. case 'D':
  1622. Expect ("DOCTYPE");
  1623. ReadDoctypeDecl ();
  1624. break;
  1625. default:
  1626. throw new XmlException (this as IXmlLineInfo,
  1627. "Unexpected declaration markup was found.");
  1628. }
  1629. }
  1630. // The reader is positioned on the first character after
  1631. // the leading '<!--'.
  1632. private void ReadComment ()
  1633. {
  1634. if (currentState == XmlNodeType.None)
  1635. currentState = XmlNodeType.XmlDeclaration;
  1636. ClearValueBuffer ();
  1637. while (PeekChar () != -1) {
  1638. int ch = ReadChar ();
  1639. if (ch == '-' && PeekChar () == '-') {
  1640. ReadChar ();
  1641. if (PeekChar () != '>')
  1642. throw new XmlException (this as IXmlLineInfo,"comments cannot contain '--'");
  1643. ReadChar ();
  1644. break;
  1645. }
  1646. if (XmlConstructs.IsInvalid (ch))
  1647. throw new XmlException (this as IXmlLineInfo,
  1648. "Not allowed character was found.");
  1649. AppendValueChar ((char)ch);
  1650. }
  1651. SetProperties (
  1652. XmlNodeType.Comment, // nodeType
  1653. String.Empty, // name
  1654. false, // isEmptyElement
  1655. true, // clearAttributes
  1656. valueBuffer // value
  1657. );
  1658. }
  1659. // The reader is positioned on the first character after
  1660. // the leading '<![CDATA['.
  1661. private void ReadCDATA ()
  1662. {
  1663. if (currentState != XmlNodeType.Element)
  1664. throw new XmlException (this as IXmlLineInfo,
  1665. "CDATA section cannot appear in this state.");
  1666. ClearValueBuffer ();
  1667. bool skip = false;
  1668. int ch = 0;
  1669. while (PeekChar () != -1) {
  1670. if (!skip)
  1671. ch = ReadChar ();
  1672. skip = false;
  1673. if (ch == ']' && PeekChar () == ']') {
  1674. ch = ReadChar (); // ']'
  1675. if (PeekChar () == '>') {
  1676. ReadChar (); // '>'
  1677. break;
  1678. } else {
  1679. skip = true;
  1680. // AppendValueChar (']');
  1681. // AppendValueChar (']');
  1682. // ch = ReadChar ();
  1683. }
  1684. }
  1685. AppendValueChar ((char)ch);
  1686. }
  1687. SetProperties (
  1688. XmlNodeType.CDATA, // nodeType
  1689. String.Empty, // name
  1690. false, // isEmptyElement
  1691. true, // clearAttributes
  1692. valueBuffer // value
  1693. );
  1694. }
  1695. // The reader is positioned on the first character after
  1696. // the leading '<!DOCTYPE'.
  1697. private void ReadDoctypeDecl ()
  1698. {
  1699. switch (currentState) {
  1700. case XmlNodeType.DocumentType:
  1701. case XmlNodeType.Element:
  1702. case XmlNodeType.EndElement:
  1703. throw new XmlException (this as IXmlLineInfo,
  1704. "Document type cannot appear in this state.");
  1705. }
  1706. currentState = XmlNodeType.DocumentType;
  1707. string doctypeName = null;
  1708. string publicId = null;
  1709. string systemId = null;
  1710. int intSubsetStartLine = 0;
  1711. int intSubsetStartColumn = 0;
  1712. SkipWhitespace ();
  1713. doctypeName = ReadName ();
  1714. SkipWhitespace ();
  1715. switch(PeekChar ())
  1716. {
  1717. case 'S':
  1718. systemId = ReadSystemLiteral (true);
  1719. break;
  1720. case 'P':
  1721. publicId = ReadPubidLiteral ();
  1722. if (!SkipWhitespace ())
  1723. throw new XmlException (this as IXmlLineInfo,
  1724. "Whitespace is required between PUBLIC id and SYSTEM id.");
  1725. systemId = ReadSystemLiteral (false);
  1726. break;
  1727. }
  1728. SkipWhitespace ();
  1729. if(PeekChar () == '[')
  1730. {
  1731. // read markupdecl etc. or end of decl
  1732. ReadChar ();
  1733. intSubsetStartLine = this.LineNumber;
  1734. intSubsetStartColumn = this.LinePosition;
  1735. int startPos = currentTag.Length;
  1736. ReadInternalSubset ();
  1737. int endPos = currentTag.Length - 1;
  1738. parserContext.InternalSubset = currentTag.ToString (startPos, endPos - startPos);
  1739. }
  1740. // end of DOCTYPE decl.
  1741. SkipWhitespace ();
  1742. Expect ('>');
  1743. GenerateDTDObjectModel (doctypeName, publicId,
  1744. systemId, parserContext.InternalSubset,
  1745. intSubsetStartLine, intSubsetStartColumn);
  1746. // set properties for <!DOCTYPE> node
  1747. SetProperties (
  1748. XmlNodeType.DocumentType, // nodeType
  1749. doctypeName, // name
  1750. false, // isEmptyElement
  1751. parserContext.InternalSubset, // value
  1752. true // clearAttributes
  1753. );
  1754. if (publicId != null)
  1755. AddAttribute ("PUBLIC", publicId);
  1756. if (systemId != null)
  1757. AddAttribute ("SYSTEM", systemId);
  1758. }
  1759. internal DTDObjectModel GenerateDTDObjectModel (string name, string publicId,
  1760. string systemId, string internalSubset)
  1761. {
  1762. return GenerateDTDObjectModel (name, publicId, systemId, internalSubset, 0, 0);
  1763. }
  1764. internal DTDObjectModel GenerateDTDObjectModel (string name, string publicId,
  1765. string systemId, string internalSubset, int intSubsetStartLine, int intSubsetStartColumn)
  1766. {
  1767. // now compile DTD
  1768. parserContext.Dtd = new DTDObjectModel (this.NameTable); // merges both internal and external subsets in the meantime,
  1769. DTD.BaseURI = BaseURI;
  1770. DTD.Name = name;
  1771. DTD.PublicId = publicId;
  1772. DTD.SystemId = systemId;
  1773. DTD.InternalSubset = internalSubset;
  1774. DTD.XmlResolver = resolver;
  1775. DTD.IsStandalone = isStandalone;
  1776. DTD.LineNumber = line;
  1777. DTD.LinePosition = column;
  1778. return new DTDReader (DTD, intSubsetStartLine, intSubsetStartColumn).GenerateDTDObjectModel ();
  1779. }
  1780. private enum DtdInputState
  1781. {
  1782. Free = 1,
  1783. ElementDecl,
  1784. AttlistDecl,
  1785. EntityDecl,
  1786. NotationDecl,
  1787. PI,
  1788. Comment,
  1789. InsideSingleQuoted,
  1790. InsideDoubleQuoted,
  1791. }
  1792. private class DtdInputStateStack
  1793. {
  1794. Stack intern = new Stack ();
  1795. public DtdInputStateStack ()
  1796. {
  1797. Push (DtdInputState.Free);
  1798. }
  1799. public DtdInputState Peek ()
  1800. {
  1801. return (DtdInputState) intern.Peek ();
  1802. }
  1803. public DtdInputState Pop ()
  1804. {
  1805. return (DtdInputState) intern.Pop ();
  1806. }
  1807. public void Push (DtdInputState val)
  1808. {
  1809. intern.Push (val);
  1810. }
  1811. }
  1812. DtdInputStateStack stateStack = new DtdInputStateStack ();
  1813. DtdInputState State {
  1814. get { return stateStack.Peek (); }
  1815. }
  1816. // Simply read but not generate any result.
  1817. private void ReadInternalSubset ()
  1818. {
  1819. bool continueParse = true;
  1820. while (continueParse) {
  1821. switch (ReadChar ()) {
  1822. case ']':
  1823. switch (State) {
  1824. case DtdInputState.Free:
  1825. continueParse = false;
  1826. break;
  1827. case DtdInputState.InsideDoubleQuoted:
  1828. continue;
  1829. case DtdInputState.InsideSingleQuoted:
  1830. continue;
  1831. default:
  1832. throw new XmlException (this as IXmlLineInfo,"unexpected end of file at DTD.");
  1833. }
  1834. break;
  1835. case -1:
  1836. throw new XmlException (this as IXmlLineInfo,"unexpected end of file at DTD.");
  1837. case '<':
  1838. if (State == DtdInputState.InsideDoubleQuoted ||
  1839. State == DtdInputState.InsideSingleQuoted)
  1840. continue; // well-formed
  1841. switch (ReadChar ()) {
  1842. case '?':
  1843. stateStack.Push (DtdInputState.PI);
  1844. break;
  1845. case '!':
  1846. switch (ReadChar ()) {
  1847. case 'E':
  1848. switch (ReadChar ()) {
  1849. case 'L':
  1850. Expect ("EMENT");
  1851. stateStack.Push (DtdInputState.ElementDecl);
  1852. break;
  1853. case 'N':
  1854. Expect ("TITY");
  1855. stateStack.Push (DtdInputState.EntityDecl);
  1856. break;
  1857. default:
  1858. throw new XmlException (this as IXmlLineInfo,"unexpected token '<!E'.");
  1859. }
  1860. break;
  1861. case 'A':
  1862. Expect ("TTLIST");
  1863. stateStack.Push (DtdInputState.AttlistDecl);
  1864. break;
  1865. case 'N':
  1866. Expect ("OTATION");
  1867. stateStack.Push (DtdInputState.NotationDecl);
  1868. break;
  1869. case '-':
  1870. Expect ("-");
  1871. stateStack.Push (DtdInputState.Comment);
  1872. break;
  1873. }
  1874. break;
  1875. default:
  1876. throw new XmlException (this as IXmlLineInfo,"unexpected '>'.");
  1877. }
  1878. break;
  1879. case '\'':
  1880. if (State == DtdInputState.InsideSingleQuoted)
  1881. stateStack.Pop ();
  1882. else if (State != DtdInputState.InsideDoubleQuoted && State != DtdInputState.Comment)
  1883. stateStack.Push (DtdInputState.InsideSingleQuoted);
  1884. break;
  1885. case '"':
  1886. if (State == DtdInputState.InsideDoubleQuoted)
  1887. stateStack.Pop ();
  1888. else if (State != DtdInputState.InsideSingleQuoted && State != DtdInputState.Comment)
  1889. stateStack.Push (DtdInputState.InsideDoubleQuoted);
  1890. break;
  1891. case '>':
  1892. switch (State) {
  1893. case DtdInputState.ElementDecl:
  1894. goto case DtdInputState.NotationDecl;
  1895. case DtdInputState.AttlistDecl:
  1896. goto case DtdInputState.NotationDecl;
  1897. case DtdInputState.EntityDecl:
  1898. goto case DtdInputState.NotationDecl;
  1899. case DtdInputState.NotationDecl:
  1900. stateStack.Pop ();
  1901. break;
  1902. case DtdInputState.InsideDoubleQuoted:
  1903. continue;
  1904. case DtdInputState.InsideSingleQuoted:
  1905. continue; // well-formed
  1906. case DtdInputState.Comment:
  1907. continue;
  1908. default:
  1909. throw new XmlException (this as IXmlLineInfo,"unexpected token '>'");
  1910. }
  1911. break;
  1912. case '?':
  1913. if (State == DtdInputState.PI) {
  1914. if (ReadChar () == '>')
  1915. stateStack.Pop ();
  1916. }
  1917. break;
  1918. case '-':
  1919. if (State == DtdInputState.Comment) {
  1920. if (PeekChar () == '-') {
  1921. ReadChar ();
  1922. Expect ('>');
  1923. stateStack.Pop ();
  1924. }
  1925. }
  1926. break;
  1927. case '%':
  1928. if (State != DtdInputState.Free && State != DtdInputState.EntityDecl && State != DtdInputState.Comment && State != DtdInputState.InsideDoubleQuoted && State != DtdInputState.InsideSingleQuoted)
  1929. throw new XmlException (this as IXmlLineInfo,"Parameter Entity Reference cannot appear as a part of markupdecl (see XML spec 2.8).");
  1930. break;
  1931. }
  1932. }
  1933. }
  1934. // The reader is positioned on the first 'S' of "SYSTEM".
  1935. private string ReadSystemLiteral (bool expectSYSTEM)
  1936. {
  1937. if(expectSYSTEM) {
  1938. Expect ("SYSTEM");
  1939. if (!SkipWhitespace ())
  1940. throw new XmlException (this as IXmlLineInfo,
  1941. "Whitespace is required after 'SYSTEM'.");
  1942. }
  1943. else
  1944. SkipWhitespace ();
  1945. int quoteChar = ReadChar (); // apos or quot
  1946. int startPos = currentTag.Length;
  1947. int c = 0;
  1948. ClearValueBuffer ();
  1949. while (c != quoteChar) {
  1950. c = ReadChar ();
  1951. if (c < 0)
  1952. throw new XmlException (this as IXmlLineInfo,"Unexpected end of stream in ExternalID.");
  1953. if (c != quoteChar)
  1954. AppendValueChar (c);
  1955. }
  1956. return CreateValueString (); //currentTag.ToString (startPos, currentTag.Length - 1 - startPos);
  1957. }
  1958. private string ReadPubidLiteral()
  1959. {
  1960. Expect ("PUBLIC");
  1961. if (!SkipWhitespace ())
  1962. throw new XmlException (this as IXmlLineInfo,
  1963. "Whitespace is required after 'PUBLIC'.");
  1964. int quoteChar = ReadChar ();
  1965. int startPos = currentTag.Length;
  1966. int c = 0;
  1967. ClearValueBuffer ();
  1968. while(c != quoteChar)
  1969. {
  1970. c = ReadChar ();
  1971. if(c < 0) throw new XmlException (this as IXmlLineInfo,"Unexpected end of stream in ExternalID.");
  1972. if(c != quoteChar && !XmlChar.IsPubidChar (c))
  1973. throw new XmlException (this as IXmlLineInfo,"character '" + (char)c + "' not allowed for PUBLIC ID");
  1974. if (c != quoteChar)
  1975. AppendValueChar (c);
  1976. }
  1977. return CreateValueString (); //currentTag.ToString (startPos, currentTag.Length - 1 - startPos);
  1978. }
  1979. // The reader is positioned on the first character
  1980. // of the name.
  1981. internal string ReadName ()
  1982. {
  1983. return ReadNameOrNmToken(false);
  1984. }
  1985. // The reader is positioned on the first character
  1986. // of the name.
  1987. private string ReadNmToken ()
  1988. {
  1989. return ReadNameOrNmToken(true);
  1990. }
  1991. private string ReadNameOrNmToken (bool isNameToken)
  1992. {
  1993. int ch = PeekChar ();
  1994. if(isNameToken) {
  1995. if (!XmlChar.IsNameChar ((char) ch))
  1996. throw new XmlException (this as IXmlLineInfo,String.Format ("a nmtoken did not start with a legal character {0} ({1})", ch, (char)ch));
  1997. }
  1998. else {
  1999. if (!XmlChar.IsFirstNameChar (ch))
  2000. throw new XmlException (this as IXmlLineInfo,String.Format ("a name did not start with a legal character {0} ({1})", ch, (char)ch));
  2001. }
  2002. nameLength = 0;
  2003. AppendNameChar (ReadChar ());
  2004. while (XmlChar.IsNameChar (PeekChar ())) {
  2005. AppendNameChar (ReadChar ());
  2006. }
  2007. return CreateNameString ();
  2008. }
  2009. // Read the next character and compare it against the
  2010. // specified character.
  2011. private void Expect (int expected)
  2012. {
  2013. int ch = ReadChar ();
  2014. if (ch != expected) {
  2015. throw new XmlException (this as IXmlLineInfo,
  2016. String.Format (
  2017. "expected '{0}' ({1:X}) but found '{2}' ({3:X})",
  2018. (char)expected,
  2019. expected,
  2020. (char)ch,
  2021. ch));
  2022. }
  2023. }
  2024. private void Expect (string expected)
  2025. {
  2026. int len = expected.Length;
  2027. for(int i=0; i< len; i++)
  2028. Expect (expected[i]);
  2029. }
  2030. // Does not consume the first non-whitespace character.
  2031. private bool SkipWhitespace ()
  2032. {
  2033. //FIXME: Should not skip if whitespaceHandling == WhiteSpaceHandling.None
  2034. bool skipped = XmlChar.IsWhitespace (PeekChar ());
  2035. while (XmlChar.IsWhitespace (PeekChar ()))
  2036. ReadChar ();
  2037. return skipped;
  2038. }
  2039. private void ReadWhitespace ()
  2040. {
  2041. if (currentState == XmlNodeType.None)
  2042. currentState = XmlNodeType.XmlDeclaration;
  2043. ClearValueBuffer ();
  2044. int ch = PeekChar ();
  2045. do {
  2046. AppendValueChar (ReadChar ());
  2047. } while ((ch = PeekChar ()) != -1 && XmlChar.IsWhitespace (ch));
  2048. if (currentState == XmlNodeType.Element && ch != -1 && ch != '<')
  2049. ReadText (false);
  2050. else {
  2051. XmlNodeType nodeType = (this.XmlSpace == XmlSpace.Preserve) ?
  2052. XmlNodeType.SignificantWhitespace : XmlNodeType.Whitespace;
  2053. SetProperties (nodeType,
  2054. String.Empty,
  2055. false,
  2056. true,
  2057. valueBuffer);
  2058. }
  2059. return; // (PeekChar () != -1);
  2060. }
  2061. private byte GetBase64Byte (char ch)
  2062. {
  2063. switch (ch) {
  2064. case '+':
  2065. return 62;
  2066. case '/':
  2067. return 63;
  2068. case '=':
  2069. return 0;
  2070. default:
  2071. if (ch >= 'A' && ch <= 'Z')
  2072. return (byte) (ch - 'A');
  2073. else if (ch >= 'a' && ch <= 'z')
  2074. return (byte) (ch - 'a' + 26);
  2075. else if (ch >= '0' && ch <= '9')
  2076. return (byte) (ch - '0' + 52);
  2077. else
  2078. throw new XmlException ("Invalid Base64 character was found.");
  2079. }
  2080. }
  2081. // Returns -1 if it should throw an error.
  2082. private int ReadCharsInternal (char [] buffer, int offset, int length)
  2083. {
  2084. shouldSkipUntilEndTag = true;
  2085. if (offset < 0)
  2086. throw new ArgumentOutOfRangeException ("offset", offset, "Offset must be non-negative integer.");
  2087. else if (length < 0)
  2088. throw new ArgumentOutOfRangeException ("length", length, "Length must be non-negative integer.");
  2089. else if (buffer.Length < offset + length)
  2090. throw new ArgumentOutOfRangeException ("buffer length is smaller than the sum of offset and length.");
  2091. if (NodeType != XmlNodeType.Element)
  2092. return 0;
  2093. int bufIndex = offset;
  2094. for (int i = 0; i < length; i++) {
  2095. int c = PeekChar ();
  2096. switch (c) {
  2097. case -1:
  2098. throw new XmlException (this as IXmlLineInfo, "Unexpected end of xml.");
  2099. case '<':
  2100. ReadChar ();
  2101. if (PeekChar () != '/') {
  2102. buffer [bufIndex++] = '<';
  2103. continue;
  2104. }
  2105. // Seems to skip immediate EndElement
  2106. Expect ('/');
  2107. string name = ReadName ();
  2108. if (name != (string) this.elementStack.Peek ()) {
  2109. if (i + 1 < length) {
  2110. buffer [bufIndex++] = '<';
  2111. buffer [bufIndex++] = '/';
  2112. }
  2113. for (int n = 0; n < name.Length && i + n + 1 < length; n++)
  2114. buffer [bufIndex++] = name [n];
  2115. continue;
  2116. }
  2117. Expect ('>');
  2118. depth--;
  2119. this.elementStack.Pop ();
  2120. shouldSkipUntilEndTag = false;
  2121. Read ();
  2122. return i;
  2123. default:
  2124. buffer [bufIndex++] = (char) ReadChar ();
  2125. break;
  2126. }
  2127. }
  2128. return length;
  2129. }
  2130. private bool ReadUntilEndTag ()
  2131. {
  2132. int ch;
  2133. do {
  2134. ch = ReadChar ();
  2135. switch (ch) {
  2136. case -1:
  2137. throw new XmlException (this as IXmlLineInfo,
  2138. "Unexpected end of xml.");
  2139. case '<':
  2140. if (PeekChar () != '/')
  2141. continue;
  2142. ReadChar ();
  2143. string name = ReadName ();
  2144. if (name != (string) this.elementStack.Peek ())
  2145. continue;
  2146. Expect ('>');
  2147. depth--;
  2148. this.elementStack.Pop ();
  2149. return Read ();
  2150. }
  2151. } while (true);
  2152. }
  2153. #endregion
  2154. }
  2155. }