XmlTextReader.cs 73 KB

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