XmlTextReader.cs 72 KB

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