XmlTextReader.cs 66 KB

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