XmlTextReader.cs 75 KB

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