XmlTextReader.cs 74 KB

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