2
0

XmlTextReader.cs 73 KB

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