XmlTextReader.cs 73 KB

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