XmlTextReader.cs 69 KB

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