XmlTextReader.cs 67 KB

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