XmlTextReader.cs 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860
  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. #if DTD_HANDLE_EVENTS
  705. internal event ValidationEventHandler ValidationEventHandler;
  706. #endif
  707. internal DTDObjectModel DTD {
  708. get { return parserContext.Dtd; }
  709. }
  710. internal XmlResolver Resolver {
  711. get { return resolver; }
  712. }
  713. #endregion
  714. #region Privates
  715. internal class XmlTokenInfo
  716. {
  717. public XmlTokenInfo (XmlTextReader xtr, bool isPrimaryToken)
  718. {
  719. this.isPrimaryToken = isPrimaryToken;
  720. Reader = xtr;
  721. Clear ();
  722. }
  723. bool isPrimaryToken;
  724. string valueCache;
  725. protected XmlTextReader Reader;
  726. public string Name;
  727. public string LocalName;
  728. public string Prefix;
  729. public string NamespaceURI;
  730. public bool IsEmptyElement;
  731. public char QuoteChar;
  732. public int LineNumber;
  733. public int LinePosition;
  734. public int ValueBufferStart;
  735. public int ValueBufferEnd;
  736. public XmlNodeType NodeType;
  737. public virtual string Value {
  738. get {
  739. if (valueCache != null)
  740. return valueCache;
  741. if (ValueBufferStart >= 0) {
  742. //Console.WriteLine (NodeType + " / " + ValueBuffer.Length + " / " + ValueBufferStart + " / " + ValueBufferEnd);
  743. valueCache = new string (Reader.valueBuffer, ValueBufferStart, ValueBufferEnd - ValueBufferStart);
  744. return valueCache;
  745. }
  746. switch (NodeType) {
  747. case XmlNodeType.Text:
  748. case XmlNodeType.SignificantWhitespace:
  749. case XmlNodeType.Whitespace:
  750. case XmlNodeType.Comment:
  751. case XmlNodeType.CDATA:
  752. case XmlNodeType.ProcessingInstruction:
  753. valueCache = Reader.CreateValueString ();
  754. return valueCache;
  755. }
  756. return null;
  757. }
  758. set { valueCache = value; }
  759. }
  760. public virtual void Clear ()
  761. {
  762. ValueBufferStart = -1;
  763. valueCache = null;
  764. NodeType = XmlNodeType.None;
  765. Name = LocalName = Prefix = NamespaceURI = String.Empty;
  766. IsEmptyElement = false;
  767. QuoteChar = '"';
  768. LineNumber = LinePosition = 0;
  769. }
  770. internal virtual void FillNames ()
  771. {
  772. if (Reader.Namespaces) {
  773. int indexOfColon = -1;
  774. switch (NodeType) {
  775. case XmlNodeType.Attribute:
  776. case XmlNodeType.Element:
  777. case XmlNodeType.EndElement:
  778. indexOfColon = Name.IndexOf (':');
  779. break;
  780. }
  781. if (indexOfColon == -1) {
  782. Prefix = String.Empty;
  783. LocalName = Name;
  784. } else {
  785. // This improves speed by at least nearly 5%, but eats more memory at least nearly 0.3%
  786. // However, this might be reverted if NameTable got improved.
  787. // char [] nameArr = Name.ToCharArray ();
  788. // Prefix = Reader.NameTable.Add (nameArr, 0, indexOfColon);
  789. // LocalName = Reader.NameTable.Add (nameArr, indexOfColon + 1, nameArr.Length - indexOfColon - 1);
  790. Prefix = Reader.NameTable.Add (Name.Substring (0, indexOfColon));
  791. LocalName = Reader.NameTable.Add (Name.Substring (indexOfColon + 1));
  792. }
  793. // NamespaceURI
  794. switch (NodeType) {
  795. case XmlNodeType.Attribute:
  796. if (Prefix.Length == 0)
  797. NamespaceURI = string.Empty;
  798. else
  799. NamespaceURI = Reader.LookupNamespace (Prefix, true);
  800. break;
  801. case XmlNodeType.Element:
  802. case XmlNodeType.EndElement:
  803. NamespaceURI = Reader.LookupNamespace (Prefix, true);
  804. break;
  805. default:
  806. NamespaceURI = "";
  807. break;
  808. }
  809. } else {
  810. Prefix = String.Empty;
  811. LocalName = Name;
  812. }
  813. }
  814. }
  815. internal class XmlAttributeTokenInfo : XmlTokenInfo
  816. {
  817. public XmlAttributeTokenInfo (XmlTextReader reader)
  818. : base (reader, false)
  819. {
  820. NodeType = XmlNodeType.Attribute;
  821. }
  822. public int ValueTokenStartIndex;
  823. public int ValueTokenEndIndex;
  824. string valueCache;
  825. bool cachedNormalization;
  826. StringBuilder tmpBuilder = new StringBuilder ();
  827. public override string Value {
  828. get {
  829. if (cachedNormalization != Reader.Normalization)
  830. valueCache = null;
  831. if (valueCache != null)
  832. return valueCache;
  833. cachedNormalization = Reader.Normalization;
  834. // An empty value should return String.Empty.
  835. if (ValueTokenStartIndex == ValueTokenEndIndex) {
  836. XmlTokenInfo ti = Reader.attributeValueTokens [ValueTokenStartIndex];
  837. if (ti.NodeType == XmlNodeType.EntityReference)
  838. valueCache = String.Concat ("&", ti.Name, ";");
  839. else
  840. valueCache = ti.Value;
  841. if (cachedNormalization)
  842. NormalizeSpaces ();
  843. return valueCache;
  844. }
  845. tmpBuilder.Length = 0;
  846. for (int i = ValueTokenStartIndex; i <= ValueTokenEndIndex; i++) {
  847. XmlTokenInfo ti = Reader.attributeValueTokens [i];
  848. if (ti.NodeType == XmlNodeType.Text)
  849. tmpBuilder.Append (ti.Value);
  850. else {
  851. tmpBuilder.Append ('&');
  852. tmpBuilder.Append (ti.Name);
  853. tmpBuilder.Append (';');
  854. }
  855. }
  856. valueCache = tmpBuilder.ToString ();
  857. if (cachedNormalization)
  858. NormalizeSpaces ();
  859. return valueCache;
  860. }
  861. set { valueCache = value; }
  862. }
  863. public override void Clear ()
  864. {
  865. base.Clear ();
  866. valueCache = null;
  867. NodeType = XmlNodeType.Attribute;
  868. ValueTokenStartIndex = ValueTokenEndIndex = 0;
  869. }
  870. internal override void FillNames ()
  871. {
  872. base.FillNames ();
  873. if (Prefix == "xmlns" || Name == "xmlns")
  874. NamespaceURI = XmlNamespaceManager.XmlnsXmlns;
  875. }
  876. private void NormalizeSpaces ()
  877. {
  878. tmpBuilder.Length = 0;
  879. for (int i = 0; i < valueCache.Length; i++)
  880. switch (valueCache [i]) {
  881. case '\r':
  882. if (i + 1 < valueCache.Length && valueCache [i + 1] == '\n')
  883. i++;
  884. goto case '\n';
  885. case '\t':
  886. case '\n':
  887. tmpBuilder.Append (' ');
  888. break;
  889. default:
  890. tmpBuilder.Append (valueCache [i]);
  891. break;
  892. }
  893. valueCache = tmpBuilder.ToString ();
  894. }
  895. }
  896. private XmlTokenInfo cursorToken;
  897. private XmlTokenInfo currentToken;
  898. private XmlAttributeTokenInfo currentAttributeToken;
  899. private XmlTokenInfo currentAttributeValueToken;
  900. private XmlAttributeTokenInfo [] attributeTokens = new XmlAttributeTokenInfo [10];
  901. private XmlTokenInfo [] attributeValueTokens = new XmlTokenInfo [10];
  902. private int currentAttribute;
  903. private int currentAttributeValue;
  904. private int attributeCount;
  905. private XmlParserContext parserContext;
  906. private ReadState readState;
  907. private int depth;
  908. private int elementDepth;
  909. private bool depthUp;
  910. private bool popScope;
  911. private string [] elementNames;
  912. int elementNameStackPos;
  913. private bool allowMultipleRoot;
  914. private bool isStandalone;
  915. private bool returnEntityReference;
  916. private string entityReferenceName;
  917. private char [] nameBuffer;
  918. private int nameLength;
  919. private int nameCapacity;
  920. private const int initialNameCapacity = 32;
  921. private char [] valueBuffer;
  922. private int valueLength;
  923. private int valueCapacity;
  924. private const int initialValueCapacity = 256;
  925. private char [] currentTagBuffer;
  926. private int currentTagLength;
  927. private int currentTagCapacity;
  928. private const int initialCurrentTagCapacity = 256;
  929. private TextReader reader;
  930. private char [] peekChars;
  931. private int peekCharsIndex;
  932. private int peekCharsLength;
  933. private const int peekCharCapacity = 1024;
  934. private int line;
  935. private int column;
  936. private int currentLinkedNodeLineNumber;
  937. private int currentLinkedNodeLinePosition;
  938. private bool useProceedingLineInfo;
  939. private XmlNodeType startNodeType;
  940. // State machine attribute.
  941. // XmlDeclaration: after the first node.
  942. // DocumentType: after doctypedecl
  943. // Element: inside document element
  944. // EndElement: after document element
  945. private XmlNodeType currentState;
  946. // For ReadChars()/ReadBase64()/ReadBinHex()
  947. private bool shouldSkipUntilEndTag;
  948. private byte [] base64Cache = new byte [3];
  949. private int base64CacheStartsAt;
  950. // These values are never re-initialized.
  951. private bool namespaces = true;
  952. private WhitespaceHandling whitespaceHandling = WhitespaceHandling.All;
  953. private XmlResolver resolver = new XmlUrlResolver ();
  954. private bool normalization = false;
  955. private bool checkCharacters;
  956. private bool prohibitDtd = false;
  957. private bool closeInput = true;
  958. private EntityHandling entityHandling; // 2.0
  959. private void Init ()
  960. {
  961. currentToken = new XmlTokenInfo (this, true);
  962. cursorToken = currentToken;
  963. currentAttribute = -1;
  964. currentAttributeValue = -1;
  965. attributeCount = 0;
  966. readState = ReadState.Initial;
  967. allowMultipleRoot = false;
  968. depth = 0;
  969. elementDepth = 0;
  970. depthUp = false;
  971. popScope = allowMultipleRoot = false;
  972. elementNames = new string [10];
  973. elementNameStackPos = 0;
  974. isStandalone = false;
  975. returnEntityReference = false;
  976. entityReferenceName = String.Empty;
  977. nameBuffer = new char [initialNameCapacity];
  978. nameLength = 0;
  979. nameCapacity = initialNameCapacity;
  980. valueBuffer = new char [initialValueCapacity];
  981. valueLength = 0;
  982. valueCapacity = initialValueCapacity;
  983. currentTagBuffer = new char [initialCurrentTagCapacity];
  984. currentTagLength = 0;
  985. currentTagCapacity = initialCurrentTagCapacity;
  986. peekCharsIndex = 0;
  987. peekCharsLength = 0;
  988. if (peekChars == null)
  989. peekChars = new char [peekCharCapacity];
  990. line = 1;
  991. column = 1;
  992. currentTagLength = 0;
  993. currentLinkedNodeLineNumber = currentLinkedNodeLinePosition = 0;
  994. useProceedingLineInfo = false;
  995. currentState = XmlNodeType.None;
  996. shouldSkipUntilEndTag = false;
  997. base64CacheStartsAt = -1;
  998. checkCharacters = true;
  999. #if NET_2_0
  1000. if (Settings != null)
  1001. checkCharacters = Settings.CheckCharacters;
  1002. #endif
  1003. prohibitDtd = false;
  1004. closeInput = true;
  1005. entityHandling = EntityHandling.ExpandCharEntities;
  1006. }
  1007. private void InitializeContext (string url, XmlParserContext context, TextReader fragment, XmlNodeType fragType)
  1008. {
  1009. startNodeType = fragType;
  1010. parserContext = context;
  1011. if (context == null) {
  1012. XmlNameTable nt = new NameTable ();
  1013. parserContext = new XmlParserContext (nt,
  1014. new XmlNamespaceManager (nt),
  1015. String.Empty,
  1016. XmlSpace.None);
  1017. }
  1018. if (url != null && url.Length > 0) {
  1019. Uri uri = null;
  1020. try {
  1021. uri = new Uri (url);
  1022. } catch (Exception) {
  1023. string path = Path.GetFullPath ("./a");
  1024. uri = new Uri (new Uri (path), url);
  1025. }
  1026. parserContext.BaseURI = uri.ToString ();
  1027. }
  1028. Init ();
  1029. reader = fragment;
  1030. switch (fragType) {
  1031. case XmlNodeType.Attribute:
  1032. reader = new StringReader (fragment.ReadToEnd ().Replace ("\"", "&quot;"));
  1033. SkipTextDeclaration ();
  1034. break;
  1035. case XmlNodeType.Element:
  1036. currentState = XmlNodeType.Element;
  1037. allowMultipleRoot = true;
  1038. SkipTextDeclaration ();
  1039. break;
  1040. case XmlNodeType.Document:
  1041. break;
  1042. default:
  1043. throw new XmlException (String.Format ("NodeType {0} is not allowed to create XmlTextReader.", fragType));
  1044. }
  1045. }
  1046. #if NET_2_0
  1047. [MonoTODO ("Test")]
  1048. internal ConformanceLevel Conformance {
  1049. set {
  1050. if (value == ConformanceLevel.Fragment) {
  1051. currentState = XmlNodeType.Element;
  1052. allowMultipleRoot = true;
  1053. }
  1054. }
  1055. }
  1056. internal void AdjustLineInfoOffset (int lineNumberOffset, int linePositionOffset)
  1057. {
  1058. line += lineNumberOffset;
  1059. column += linePositionOffset;
  1060. }
  1061. internal void SetNameTable (XmlNameTable nameTable)
  1062. {
  1063. parserContext.NameTable = nameTable;
  1064. }
  1065. #endif
  1066. // Use this method rather than setting the properties
  1067. // directly so that all the necessary properties can
  1068. // be changed in harmony with each other. Maybe the
  1069. // fields should be in a seperate class to help enforce
  1070. // this.
  1071. private void SetProperties (
  1072. XmlNodeType nodeType,
  1073. string name,
  1074. bool isEmptyElement,
  1075. string value,
  1076. bool clearAttributes)
  1077. {
  1078. SetProperties (currentToken, nodeType, name, isEmptyElement, value, clearAttributes);
  1079. currentToken.LineNumber = this.currentLinkedNodeLineNumber;
  1080. currentToken.LinePosition = this.currentLinkedNodeLinePosition;
  1081. }
  1082. private void SetProperties (
  1083. XmlTokenInfo token,
  1084. XmlNodeType nodeType,
  1085. string name,
  1086. bool isEmptyElement,
  1087. string value,
  1088. bool clearAttributes)
  1089. {
  1090. token.Clear ();
  1091. token.NodeType = nodeType;
  1092. token.Name = name;
  1093. token.IsEmptyElement = isEmptyElement;
  1094. token.Value = value;
  1095. this.elementDepth = depth;
  1096. if (clearAttributes)
  1097. ClearAttributes ();
  1098. token.FillNames ();
  1099. }
  1100. private void ClearAttributes ()
  1101. {
  1102. for (int i = 0; i < attributeCount; i++)
  1103. attributeTokens [i].Clear ();
  1104. attributeCount = 0;
  1105. currentAttribute = -1;
  1106. currentAttributeValue = -1;
  1107. }
  1108. private int PeekChar ()
  1109. {
  1110. if (peekCharsLength == peekCharsIndex) {
  1111. if (!ReadTextReader ())
  1112. return -1;
  1113. return PeekChar ();
  1114. }
  1115. else {
  1116. char c = peekChars [peekCharsIndex];
  1117. if (c != 0) return c;
  1118. else return -1;
  1119. }
  1120. }
  1121. private int ReadChar ()
  1122. {
  1123. int ch;
  1124. if (peekCharsLength == peekCharsIndex) {
  1125. if (!ReadTextReader ())
  1126. return -1;
  1127. return ReadChar ();
  1128. }
  1129. ch = peekChars [peekCharsIndex++];
  1130. if (ch == '\n') {
  1131. line++;
  1132. column = 1;
  1133. } else if (ch == 0) {
  1134. return -1;
  1135. } else {
  1136. column++;
  1137. }
  1138. if (currentState != XmlNodeType.Element)
  1139. AppendCurrentTagChar (ch);
  1140. return ch;
  1141. }
  1142. private bool ReadTextReader ()
  1143. {
  1144. peekCharsIndex = 0;
  1145. peekCharsLength = reader.Read (peekChars, 0, peekCharCapacity);
  1146. if (peekCharsLength == 0)
  1147. return false;
  1148. return true;
  1149. }
  1150. private string ExpandSurrogateChar (int ch)
  1151. {
  1152. if (ch < Char.MaxValue)
  1153. return ((char) ch).ToString ();
  1154. else {
  1155. char [] tmp = new char [] {(char) (ch / 0x10000 + 0xD800 - 1), (char) (ch % 0x10000 + 0xDC00)};
  1156. return new string (tmp);
  1157. }
  1158. }
  1159. // This should really keep track of some state so
  1160. // that it's not possible to have more than one document
  1161. // element or text outside of the document element.
  1162. private bool ReadContent ()
  1163. {
  1164. currentTagLength = 0;
  1165. if (popScope) {
  1166. parserContext.NamespaceManager.PopScope ();
  1167. popScope = false;
  1168. }
  1169. if (returnEntityReference)
  1170. SetEntityReferenceProperties ();
  1171. else {
  1172. int c = PeekChar ();
  1173. if (c == -1) {
  1174. readState = ReadState.EndOfFile;
  1175. ClearValueBuffer ();
  1176. SetProperties (
  1177. XmlNodeType.None, // nodeType
  1178. String.Empty, // name
  1179. false, // isEmptyElement
  1180. null, // value
  1181. true // clearAttributes
  1182. );
  1183. if (depth > 0)
  1184. throw new XmlException ("unexpected end of file. Current depth is " + depth);
  1185. return false;
  1186. } else {
  1187. switch (c) {
  1188. case '<':
  1189. ReadChar ();
  1190. switch (PeekChar ())
  1191. {
  1192. case '/':
  1193. ReadChar ();
  1194. ReadEndTag ();
  1195. break;
  1196. case '?':
  1197. ReadChar ();
  1198. ReadProcessingInstruction ();
  1199. break;
  1200. case '!':
  1201. ReadChar ();
  1202. ReadDeclaration ();
  1203. break;
  1204. default:
  1205. ReadStartTag ();
  1206. break;
  1207. }
  1208. break;
  1209. case '\r': goto case ' ';
  1210. case '\n': goto case ' ';
  1211. case '\t': goto case ' ';
  1212. case ' ':
  1213. if (whitespaceHandling == WhitespaceHandling.All ||
  1214. whitespaceHandling == WhitespaceHandling.Significant)
  1215. ReadWhitespace ();
  1216. else {
  1217. SkipWhitespace ();
  1218. return ReadContent ();
  1219. }
  1220. break;
  1221. default:
  1222. ReadText (true);
  1223. break;
  1224. }
  1225. }
  1226. }
  1227. return this.ReadState != ReadState.EndOfFile;
  1228. }
  1229. private void SetEntityReferenceProperties ()
  1230. {
  1231. DTDEntityDeclaration decl = DTD != null ? DTD.EntityDecls [entityReferenceName] : null;
  1232. if (this.isStandalone)
  1233. if (DTD == null || decl == null || !decl.IsInternalSubset)
  1234. throw new XmlException (this as IXmlLineInfo,
  1235. "Standalone document must not contain any references to an non-internally declared entity.");
  1236. if (decl != null && decl.NotationName != null)
  1237. throw new XmlException (this as IXmlLineInfo,
  1238. "Reference to any unparsed entities is not allowed here.");
  1239. ClearValueBuffer ();
  1240. SetProperties (
  1241. XmlNodeType.EntityReference, // nodeType
  1242. entityReferenceName, // name
  1243. false, // isEmptyElement
  1244. null, // value
  1245. true // clearAttributes
  1246. );
  1247. returnEntityReference = false;
  1248. entityReferenceName = String.Empty;
  1249. }
  1250. // The leading '<' has already been consumed.
  1251. private void ReadStartTag ()
  1252. {
  1253. if (currentState == XmlNodeType.EndElement)
  1254. throw new XmlException (this as IXmlLineInfo,
  1255. "Multiple document element was detected.");
  1256. currentState = XmlNodeType.Element;
  1257. parserContext.NamespaceManager.PushScope ();
  1258. currentLinkedNodeLineNumber = line;
  1259. currentLinkedNodeLinePosition = column;
  1260. string name = ReadName ();
  1261. if (currentState == XmlNodeType.EndElement)
  1262. throw new XmlException (this as IXmlLineInfo,"document has terminated, cannot open new element");
  1263. bool isEmptyElement = false;
  1264. ClearAttributes ();
  1265. SkipWhitespace ();
  1266. if (XmlChar.IsFirstNameChar (PeekChar ()))
  1267. ReadAttributes (false);
  1268. cursorToken = this.currentToken;
  1269. // fill namespaces
  1270. for (int i = 0; i < attributeCount; i++)
  1271. attributeTokens [i].FillNames ();
  1272. // quick name check
  1273. for (int i = 0; i < attributeCount; i++) {
  1274. for (int j = i + 1; j < attributeCount; j++)
  1275. if (Object.ReferenceEquals (attributeTokens [i].Name, attributeTokens [j].Name) ||
  1276. (Object.ReferenceEquals (attributeTokens [i].LocalName, attributeTokens [j].LocalName) &&
  1277. Object.ReferenceEquals (attributeTokens [i].NamespaceURI, attributeTokens [j].NamespaceURI)))
  1278. throw new XmlException (this as IXmlLineInfo,
  1279. "Attribute name and qualified name must be identical.");
  1280. }
  1281. string baseUri = GetAttribute ("xml:base");
  1282. if (baseUri != null) {
  1283. if (this.resolver != null)
  1284. parserContext.BaseURI = resolver.ResolveUri (new Uri (BaseURI), baseUri).ToString ();
  1285. else
  1286. parserContext.BaseURI = baseUri;
  1287. }
  1288. string xmlLang = GetAttribute ("xml:lang");
  1289. if (xmlLang != null)
  1290. parserContext.XmlLang = xmlLang;
  1291. string xmlSpaceAttr = GetAttribute ("xml:space");
  1292. if (xmlSpaceAttr != null) {
  1293. if (xmlSpaceAttr == "preserve")
  1294. parserContext.XmlSpace = XmlSpace.Preserve;
  1295. else if (xmlSpaceAttr == "default")
  1296. parserContext.XmlSpace = XmlSpace.Default;
  1297. else
  1298. throw new XmlException (this as IXmlLineInfo,String.Format ("Invalid xml:space value: {0}", xmlSpaceAttr));
  1299. }
  1300. if (PeekChar () == '/') {
  1301. ReadChar ();
  1302. isEmptyElement = true;
  1303. popScope = true;
  1304. }
  1305. else {
  1306. depthUp = true;
  1307. PushElementName (name);
  1308. parserContext.PushScope ();
  1309. }
  1310. Expect ('>');
  1311. SetProperties (
  1312. XmlNodeType.Element, // nodeType
  1313. name, // name
  1314. isEmptyElement, // isEmptyElement
  1315. null, // value
  1316. false // clearAttributes
  1317. );
  1318. if (LookupNamespace (Prefix) == null)
  1319. throw new XmlException (String.Format ("'{0}' is undeclared namespace.", Prefix));
  1320. try {
  1321. for (int i = 0; i < attributeCount; i++) {
  1322. MoveToAttribute (i);
  1323. if (LookupNamespace (Prefix) == null)
  1324. throw new XmlException (String.Format ("'{0}' is undeclared namespace.", Prefix));
  1325. }
  1326. } finally {
  1327. MoveToElement ();
  1328. }
  1329. if (IsEmptyElement)
  1330. CheckCurrentStateUpdate ();
  1331. }
  1332. private void PushElementName (string name)
  1333. {
  1334. if (elementNames.Length == elementNameStackPos) {
  1335. string [] newArray = new string [elementNames.Length * 2];
  1336. Array.Copy (elementNames, 0, newArray, 0, elementNameStackPos);
  1337. elementNames = newArray;
  1338. }
  1339. elementNames [elementNameStackPos++] = name;
  1340. }
  1341. // The reader is positioned on the first character
  1342. // of the element's name.
  1343. private void ReadEndTag ()
  1344. {
  1345. if (currentState != XmlNodeType.Element)
  1346. throw new XmlException (this as IXmlLineInfo,
  1347. "End tag cannot appear in this state.");
  1348. currentLinkedNodeLineNumber = line;
  1349. currentLinkedNodeLinePosition = column;
  1350. string name = ReadName ();
  1351. if (elementNameStackPos == 0)
  1352. throw new XmlException (this as IXmlLineInfo,"closing element without matching opening element");
  1353. string expected = elementNames [--elementNameStackPos];
  1354. if (expected != name)
  1355. throw new XmlException (this as IXmlLineInfo,String.Format ("unmatched closing element: expected {0} but found {1}", expected, name));
  1356. parserContext.PopScope ();
  1357. ExpectAfterWhitespace ('>');
  1358. --depth;
  1359. SetProperties (
  1360. XmlNodeType.EndElement, // nodeType
  1361. name, // name
  1362. false, // isEmptyElement
  1363. null, // value
  1364. true // clearAttributes
  1365. );
  1366. popScope = true;
  1367. CheckCurrentStateUpdate ();
  1368. }
  1369. private void CheckCurrentStateUpdate ()
  1370. {
  1371. if (depth == 0 && !allowMultipleRoot && (IsEmptyElement || NodeType == XmlNodeType.EndElement))
  1372. currentState = XmlNodeType.EndElement;
  1373. }
  1374. private void AppendNameChar (int ch)
  1375. {
  1376. if (nameLength == nameCapacity)
  1377. ExpandNameCapacity ();
  1378. if (ch < Char.MaxValue)
  1379. nameBuffer [nameLength++] = (char) ch;
  1380. else {
  1381. nameBuffer [nameLength++] = (char) (ch / 0x10000 + 0xD800 - 1);
  1382. if (nameLength == nameCapacity)
  1383. ExpandNameCapacity ();
  1384. nameBuffer [nameLength++] = (char) (ch % 0x10000 + 0xDC00);
  1385. }
  1386. }
  1387. private void ExpandNameCapacity ()
  1388. {
  1389. nameCapacity = nameCapacity * 2;
  1390. char [] oldNameBuffer = nameBuffer;
  1391. nameBuffer = new char [nameCapacity];
  1392. Array.Copy (oldNameBuffer, nameBuffer, nameLength);
  1393. }
  1394. private void AppendValueChar (int ch)
  1395. {
  1396. if (valueLength == valueCapacity)
  1397. ExpandValueCapacity ();
  1398. if (ch < Char.MaxValue)
  1399. valueBuffer [valueLength++] = (char) ch;
  1400. else {
  1401. valueBuffer [valueLength++] = (char) (ch / 0x10000 + 0xD800 - 1);
  1402. if (valueLength == valueCapacity)
  1403. ExpandValueCapacity ();
  1404. valueBuffer [valueLength++] = (char) (ch % 0x10000 + 0xDC00);
  1405. }
  1406. }
  1407. private void ExpandValueCapacity ()
  1408. {
  1409. valueCapacity = valueCapacity * 2;
  1410. char [] oldValueBuffer = valueBuffer;
  1411. valueBuffer = new char [valueCapacity];
  1412. Array.Copy (oldValueBuffer, valueBuffer, valueLength);
  1413. }
  1414. private string CreateValueString ()
  1415. {
  1416. return new string (valueBuffer, 0, valueLength);
  1417. }
  1418. private void ClearValueBuffer ()
  1419. {
  1420. valueLength = 0;
  1421. }
  1422. private void AppendCurrentTagChar (int ch)
  1423. {
  1424. if (currentTagLength == currentTagCapacity)
  1425. ExpandCurrentTagCapacity ();
  1426. if (ch < Char.MaxValue)
  1427. currentTagBuffer [currentTagLength++] = (char) ch;
  1428. else {
  1429. currentTagBuffer [currentTagLength++] = (char) (ch / 0x10000 + 0xD800 - 1);
  1430. if (currentTagLength == currentTagCapacity)
  1431. ExpandCurrentTagCapacity ();
  1432. currentTagBuffer [currentTagLength++] = (char) (ch % 0x10000 + 0xDC00);
  1433. }
  1434. }
  1435. private void ExpandCurrentTagCapacity ()
  1436. {
  1437. currentTagCapacity = currentTagCapacity * 2;
  1438. char [] oldCurrentTagBuffer = currentTagBuffer;
  1439. currentTagBuffer = new char [currentTagCapacity];
  1440. Array.Copy (oldCurrentTagBuffer, currentTagBuffer, currentTagLength);
  1441. }
  1442. private string CreateCurrentTagString ()
  1443. {
  1444. return new string (currentTagBuffer, 0, currentTagLength);
  1445. }
  1446. private void ClearCurrentTagBuffer ()
  1447. {
  1448. currentTagLength = 0;
  1449. }
  1450. // The reader is positioned on the first character
  1451. // of the text.
  1452. private void ReadText (bool notWhitespace)
  1453. {
  1454. if (currentState != XmlNodeType.Element)
  1455. throw new XmlException (this as IXmlLineInfo,
  1456. "Text node cannot appear in this state.");
  1457. if (notWhitespace)
  1458. ClearValueBuffer ();
  1459. int ch = PeekChar ();
  1460. bool previousWasCloseBracket = false;
  1461. while (ch != '<' && ch != -1) {
  1462. if (ch == '&') {
  1463. ReadChar ();
  1464. ch = ReadReference (false);
  1465. if (returnEntityReference) // Returns -1 if char validation should not be done
  1466. break;
  1467. } else if (normalization && ch == '\r') {
  1468. ReadChar ();
  1469. ch = ReadChar ();
  1470. if (ch != '\n')
  1471. // append '\n' instead of '\r'.
  1472. AppendValueChar ('\n');
  1473. // and in case of "\r\n", discard '\r'.
  1474. } else {
  1475. if (CharacterChecking && XmlChar.IsInvalid (ch))
  1476. throw new XmlException (this, "Not allowed character was found.");
  1477. ch = ReadChar ();
  1478. }
  1479. AppendValueChar (ch);
  1480. // Block "]]>"
  1481. if (ch == ']') {
  1482. if (previousWasCloseBracket)
  1483. if (PeekChar () == '>')
  1484. throw new XmlException (this as IXmlLineInfo,
  1485. "Inside text content, character sequence ']]>' is not allowed.");
  1486. previousWasCloseBracket = true;
  1487. }
  1488. else if (previousWasCloseBracket)
  1489. previousWasCloseBracket = false;
  1490. ch = PeekChar ();
  1491. notWhitespace = true;
  1492. }
  1493. if (returnEntityReference && valueLength == 0) {
  1494. SetEntityReferenceProperties ();
  1495. } else {
  1496. XmlNodeType nodeType = notWhitespace ? XmlNodeType.Text :
  1497. this.XmlSpace == XmlSpace.Preserve ? XmlNodeType.SignificantWhitespace : XmlNodeType.Whitespace;
  1498. SetProperties (
  1499. nodeType, // nodeType
  1500. String.Empty, // name
  1501. false, // isEmptyElement
  1502. null, // value: create only when required
  1503. true // clearAttributes
  1504. );
  1505. }
  1506. }
  1507. // The leading '&' has already been consumed.
  1508. // Returns true if the entity reference isn't a simple
  1509. // character reference or one of the predefined entities.
  1510. // This allows the ReadText method to break so that the
  1511. // next call to Read will return the EntityReference node.
  1512. private int ReadReference (bool ignoreEntityReferences)
  1513. {
  1514. if (PeekChar () == '#') {
  1515. ReadChar ();
  1516. return ReadCharacterReference ();
  1517. } else
  1518. return ReadEntityReference (ignoreEntityReferences);
  1519. }
  1520. private int ReadCharacterReference ()
  1521. {
  1522. int value = 0;
  1523. if (PeekChar () == 'x') {
  1524. ReadChar ();
  1525. while (PeekChar () != ';' && PeekChar () != -1) {
  1526. int ch = ReadChar ();
  1527. if (ch >= '0' && ch <= '9')
  1528. value = (value << 4) + ch - '0';
  1529. else if (ch >= 'A' && ch <= 'F')
  1530. value = (value << 4) + ch - 'A' + 10;
  1531. else if (ch >= 'a' && ch <= 'f')
  1532. value = (value << 4) + ch - 'a' + 10;
  1533. else
  1534. throw new XmlException (this as IXmlLineInfo,
  1535. String.Format (CultureInfo.InvariantCulture,
  1536. "invalid hexadecimal digit: {0} (#x{1:X})",
  1537. (char) ch,
  1538. ch));
  1539. }
  1540. } else {
  1541. while (PeekChar () != ';' && PeekChar () != -1) {
  1542. int ch = ReadChar ();
  1543. if (ch >= '0' && ch <= '9')
  1544. value = value * 10 + ch - '0';
  1545. else
  1546. throw new XmlException (this as IXmlLineInfo,
  1547. String.Format (CultureInfo.InvariantCulture,
  1548. "invalid decimal digit: {0} (#x{1:X})",
  1549. (char) ch,
  1550. ch));
  1551. }
  1552. }
  1553. ReadChar (); // ';'
  1554. // There is no way to save surrogate pairs...
  1555. if (CharacterChecking && XmlChar.IsInvalid (value))
  1556. throw new XmlException (this as IXmlLineInfo,
  1557. "Referenced character was not allowed in XML. Normalization is " + normalization + ", checkCharacters = " + checkCharacters);
  1558. return value;
  1559. }
  1560. // Returns -1 if it should not be validated.
  1561. // Real EOF must not be detected here.
  1562. private int ReadEntityReference (bool ignoreEntityReferences)
  1563. {
  1564. string name = ReadName ();
  1565. Expect (';');
  1566. int predefined = XmlChar.GetPredefinedEntity (name);
  1567. if (predefined >= 0)
  1568. return predefined;
  1569. else {
  1570. if (ignoreEntityReferences) {
  1571. AppendValueChar ('&');
  1572. for (int i = 0; i < name.Length; i++)
  1573. AppendValueChar (name [i]);
  1574. AppendValueChar (';');
  1575. } else {
  1576. returnEntityReference = true;
  1577. entityReferenceName = name;
  1578. }
  1579. }
  1580. return -1;
  1581. }
  1582. // The reader is positioned on the first character of
  1583. // the attribute name.
  1584. private void ReadAttributes (bool isXmlDecl)
  1585. {
  1586. int peekChar = -1;
  1587. bool requireWhitespace = false;
  1588. currentAttribute = -1;
  1589. currentAttributeValue = -1;
  1590. do {
  1591. if (!SkipWhitespace () && requireWhitespace)
  1592. throw new XmlException ("Unexpected token. Name is required here.");
  1593. IncrementAttributeToken ();
  1594. currentAttributeToken.LineNumber = line;
  1595. currentAttributeToken.LinePosition = column;
  1596. currentAttributeToken.LocalName =
  1597. currentAttributeToken.Name = ReadName ();
  1598. ExpectAfterWhitespace ('=');
  1599. SkipWhitespace ();
  1600. ReadAttributeValueTokens (-1);
  1601. // This hack is required for xmldecl which has
  1602. // both effective attributes and Value.
  1603. string dummyValue;
  1604. if (isXmlDecl)
  1605. dummyValue = currentAttributeToken.Value;
  1606. attributeCount++;
  1607. if (currentAttributeToken.Name == "xmlns")
  1608. parserContext.NamespaceManager.AddNamespace (String.Empty, GetAttribute (currentAttribute));
  1609. else if (currentAttributeToken.Name.StartsWith ("xmlns:")) {
  1610. string nsPrefix = currentAttributeToken.Name.Substring (6);
  1611. parserContext.NamespaceManager.AddNamespace (nsPrefix, GetAttribute (currentAttribute));
  1612. }
  1613. if (!SkipWhitespace ())
  1614. requireWhitespace = true;
  1615. peekChar = PeekChar ();
  1616. if (isXmlDecl) {
  1617. if (peekChar == '?')
  1618. break;
  1619. }
  1620. else if (peekChar == '/' || peekChar == '>')
  1621. break;
  1622. } while (peekChar != -1);
  1623. currentAttribute = -1;
  1624. currentAttributeValue = -1;
  1625. }
  1626. private void AddAttribute (string name, string value)
  1627. {
  1628. IncrementAttributeToken ();
  1629. XmlAttributeTokenInfo ati = attributeTokens [currentAttribute];
  1630. ati.Name = "SYSTEM";
  1631. ati.FillNames ();
  1632. IncrementAttributeValueToken ();
  1633. XmlTokenInfo vti = attributeValueTokens [currentAttributeValue];
  1634. vti.Value = value;
  1635. SetProperties (vti, XmlNodeType.Text, String.Empty, false, value, false);
  1636. attributeCount++;
  1637. }
  1638. private void IncrementAttributeToken ()
  1639. {
  1640. currentAttribute++;
  1641. if (attributeTokens.Length == currentAttribute) {
  1642. XmlAttributeTokenInfo [] newArray =
  1643. new XmlAttributeTokenInfo [attributeTokens.Length * 2];
  1644. attributeTokens.CopyTo (newArray, 0);
  1645. attributeTokens = newArray;
  1646. }
  1647. if (attributeTokens [currentAttribute] == null)
  1648. attributeTokens [currentAttribute] = new XmlAttributeTokenInfo (this);
  1649. currentAttributeToken = attributeTokens [currentAttribute];
  1650. currentAttributeToken.Clear ();
  1651. }
  1652. private void IncrementAttributeValueToken ()
  1653. {
  1654. currentAttributeValue++;
  1655. if (attributeValueTokens.Length == currentAttributeValue) {
  1656. XmlTokenInfo [] newArray = new XmlTokenInfo [attributeValueTokens.Length * 2];
  1657. attributeValueTokens.CopyTo (newArray, 0);
  1658. attributeValueTokens = newArray;
  1659. }
  1660. if (attributeValueTokens [currentAttributeValue] == null)
  1661. attributeValueTokens [currentAttributeValue] = new XmlTokenInfo (this, false);
  1662. currentAttributeValueToken = attributeValueTokens [currentAttributeValue];
  1663. currentAttributeValueToken.Clear ();
  1664. }
  1665. // LAMESPEC: Orthodox XML reader should normalize attribute values
  1666. private void ReadAttributeValueTokens (int dummyQuoteChar)
  1667. {
  1668. int quoteChar = (dummyQuoteChar < 0) ? ReadChar () : dummyQuoteChar;
  1669. if (quoteChar != '\'' && quoteChar != '\"')
  1670. throw new XmlException (this as IXmlLineInfo,"an attribute value was not quoted");
  1671. currentAttributeToken.QuoteChar = (char) quoteChar;
  1672. IncrementAttributeValueToken ();
  1673. currentAttributeToken.ValueTokenStartIndex = currentAttributeValue;
  1674. currentAttributeValueToken.LineNumber = line;
  1675. currentAttributeValueToken.LinePosition = column;
  1676. bool incrementToken = false;
  1677. bool isNewToken = true;
  1678. bool loop = true;
  1679. int ch = 0;
  1680. currentAttributeValueToken.ValueBufferStart = valueLength;
  1681. while (loop) {
  1682. ch = ReadChar ();
  1683. if (ch == quoteChar)
  1684. break;
  1685. if (incrementToken) {
  1686. IncrementAttributeValueToken ();
  1687. currentAttributeValueToken.ValueBufferStart = valueLength;
  1688. currentAttributeValueToken.LineNumber = line;
  1689. currentAttributeValueToken.LinePosition = column;
  1690. incrementToken = false;
  1691. isNewToken = true;
  1692. }
  1693. switch (ch)
  1694. {
  1695. case '<':
  1696. throw new XmlException (this as IXmlLineInfo,"attribute values cannot contain '<'");
  1697. case -1:
  1698. if (dummyQuoteChar < 0)
  1699. throw new XmlException (this as IXmlLineInfo,"unexpected end of file in an attribute value");
  1700. else // Attribute value constructor.
  1701. loop = false;
  1702. break;
  1703. case '&':
  1704. int startPosition = currentTagLength - 1;
  1705. if (PeekChar () == '#') {
  1706. ReadChar ();
  1707. ch = ReadCharacterReference ();
  1708. if (CharacterChecking && XmlChar.IsInvalid (ch))
  1709. throw new XmlException (this as IXmlLineInfo,
  1710. "Not allowed character was found.");
  1711. AppendValueChar (ch);
  1712. break;
  1713. }
  1714. // Check XML 1.0 section 3.1 WFC.
  1715. string entName = ReadName ();
  1716. Expect (';');
  1717. int predefined = XmlChar.GetPredefinedEntity (entName);
  1718. if (predefined < 0) {
  1719. CheckAttributeEntityReferenceWFC (entName);
  1720. currentAttributeValueToken.ValueBufferEnd = valueLength;
  1721. currentAttributeValueToken.NodeType = XmlNodeType.Text;
  1722. if (!isNewToken)
  1723. IncrementAttributeValueToken ();
  1724. currentAttributeValueToken.Name = entName;
  1725. currentAttributeValueToken.Value = String.Empty;
  1726. currentAttributeValueToken.NodeType = XmlNodeType.EntityReference;
  1727. incrementToken = true;
  1728. }
  1729. else
  1730. AppendValueChar (predefined);
  1731. break;
  1732. default:
  1733. if (CharacterChecking && XmlChar.IsInvalid (ch))
  1734. throw new XmlException (this, "Invalid character was found.");
  1735. AppendValueChar (ch);
  1736. break;
  1737. }
  1738. isNewToken = false;
  1739. }
  1740. if (!incrementToken) {
  1741. currentAttributeValueToken.ValueBufferEnd = valueLength;
  1742. currentAttributeValueToken.NodeType = XmlNodeType.Text;
  1743. }
  1744. currentAttributeToken.ValueTokenEndIndex = currentAttributeValue;
  1745. }
  1746. private void CheckAttributeEntityReferenceWFC (string entName)
  1747. {
  1748. DTDEntityDeclaration entDecl =
  1749. DTD == null ? null : DTD.EntityDecls [entName];
  1750. if (DTD != null && resolver != null && entDecl == null)
  1751. throw new XmlException (this, "Referenced entity does not exist.");
  1752. if (entDecl == null)
  1753. return;
  1754. if (entDecl.HasExternalReference)
  1755. throw new XmlException (this, "Reference to external entities is not allowed in the value of an attribute.");
  1756. if (isStandalone && !entDecl.IsInternalSubset)
  1757. throw new XmlException (this, "Reference to external entities is not allowed in the internal subset.");
  1758. if (entDecl.EntityValue.IndexOf ('<') >= 0)
  1759. throw new XmlException (this, "Attribute must not contain character '<' either directly or indirectly by way of entity references.");
  1760. }
  1761. // The reader is positioned on the first character
  1762. // of the target.
  1763. //
  1764. // It may be xml declaration or processing instruction.
  1765. private void ReadProcessingInstruction ()
  1766. {
  1767. string target = ReadName ();
  1768. if (target == "xml") {
  1769. ReadXmlDeclaration ();
  1770. return;
  1771. } else if (target.ToLower (CultureInfo.InvariantCulture) == "xml")
  1772. throw new XmlException (this as IXmlLineInfo,
  1773. "Not allowed processing instruction name which starts with 'X', 'M', 'L' was found.");
  1774. if (currentState == XmlNodeType.None)
  1775. currentState = XmlNodeType.XmlDeclaration;
  1776. if (!SkipWhitespace ())
  1777. if (PeekChar () != '?')
  1778. throw new XmlException (this as IXmlLineInfo,
  1779. "Invalid processing instruction name was found.");
  1780. ClearValueBuffer ();
  1781. while (PeekChar () != -1) {
  1782. int ch = ReadChar ();
  1783. if (ch == '?' && PeekChar () == '>') {
  1784. ReadChar ();
  1785. break;
  1786. }
  1787. if (CharacterChecking && XmlChar.IsInvalid (ch))
  1788. throw new XmlException (this, "Invalid character was found.");
  1789. AppendValueChar (ch);
  1790. }
  1791. SetProperties (
  1792. XmlNodeType.ProcessingInstruction, // nodeType
  1793. target, // name
  1794. false, // isEmptyElement
  1795. null, // value: create only when required
  1796. true // clearAttributes
  1797. );
  1798. }
  1799. // The reader is positioned after "<?xml "
  1800. private void ReadXmlDeclaration ()
  1801. {
  1802. if (currentState != XmlNodeType.None) {
  1803. throw new XmlException (this as IXmlLineInfo,
  1804. "XML declaration cannot appear in this state.");
  1805. }
  1806. currentState = XmlNodeType.XmlDeclaration;
  1807. ClearAttributes ();
  1808. ReadAttributes (true); // They must have "version."
  1809. string version = GetAttribute ("version");
  1810. string message = null;
  1811. if (attributeTokens [0].Name != "version" || version != "1.0")
  1812. message = "Version 1.0 declaration is required in XML Declaration.";
  1813. else if (attributeCount > 1 &&
  1814. (attributeTokens [1].Name != "encoding" &&
  1815. attributeTokens [1].Name != "standalone"))
  1816. message = "Invalid Xml Declaration markup was found.";
  1817. else if (attributeCount > 2 && attributeTokens [2].Name != "standalone")
  1818. message = "Invalid Xml Declaration markup was found.";
  1819. string sa = GetAttribute ("standalone");
  1820. if (sa != null && sa != "yes" && sa != "no")
  1821. message = String.Format ("Only 'yes' or 'no' is allowed for standalone. Value was '{0}'", sa);
  1822. this.isStandalone = (sa == "yes");
  1823. if (message != null)
  1824. throw new XmlException (this as IXmlLineInfo, message);
  1825. SetProperties (
  1826. XmlNodeType.XmlDeclaration, // nodeType
  1827. "xml", // name
  1828. false, // isEmptyElement
  1829. new string (currentTagBuffer, 6, currentTagLength - 6), // value
  1830. false // clearAttributes
  1831. );
  1832. Expect ("?>");
  1833. }
  1834. private void SkipTextDeclaration ()
  1835. {
  1836. this.currentState = XmlNodeType.Element;
  1837. if (PeekChar () != '<')
  1838. return;
  1839. ReadChar ();
  1840. if (PeekChar () != '?') {
  1841. peekCharsIndex = 0;
  1842. return;
  1843. }
  1844. ReadChar ();
  1845. while (peekCharsIndex < 6) {
  1846. if (PeekChar () < 0)
  1847. break;
  1848. else
  1849. ReadChar ();
  1850. }
  1851. if (new string (peekChars, 2, 4) != "xml ") {
  1852. if (new string (peekChars, 2, 3).ToLower (CultureInfo.InvariantCulture) == "xml") {
  1853. throw new XmlException (this as IXmlLineInfo,
  1854. "Processing instruction name must not be character sequence 'X' 'M' 'L' with case insensitivity.");
  1855. }
  1856. peekCharsIndex = 0;
  1857. return;
  1858. }
  1859. SkipWhitespace ();
  1860. // version decl
  1861. if (PeekChar () == 'v') {
  1862. Expect ("version");
  1863. ExpectAfterWhitespace ('=');
  1864. SkipWhitespace ();
  1865. int quoteChar = ReadChar ();
  1866. char [] expect1_0 = new char [3];
  1867. int versionLength = 0;
  1868. switch (quoteChar) {
  1869. case '\'':
  1870. case '"':
  1871. while (PeekChar () != quoteChar) {
  1872. if (PeekChar () == -1)
  1873. throw new XmlException (this as IXmlLineInfo,
  1874. "Invalid version declaration inside text declaration.");
  1875. else if (versionLength == 3)
  1876. throw new XmlException (this as IXmlLineInfo,
  1877. "Invalid version number inside text declaration.");
  1878. else {
  1879. expect1_0 [versionLength] = (char) ReadChar ();
  1880. versionLength++;
  1881. if (versionLength == 3 && new String (expect1_0) != "1.0")
  1882. throw new XmlException (this as IXmlLineInfo,
  1883. "Invalid version number inside text declaration.");
  1884. }
  1885. }
  1886. ReadChar ();
  1887. SkipWhitespace ();
  1888. break;
  1889. default:
  1890. throw new XmlException (this as IXmlLineInfo,
  1891. "Invalid version declaration inside text declaration.");
  1892. }
  1893. }
  1894. if (PeekChar () == 'e') {
  1895. Expect ("encoding");
  1896. ExpectAfterWhitespace ('=');
  1897. SkipWhitespace ();
  1898. int quoteChar = ReadChar ();
  1899. switch (quoteChar) {
  1900. case '\'':
  1901. case '"':
  1902. while (PeekChar () != quoteChar)
  1903. if (ReadChar () == -1)
  1904. throw new XmlException (this as IXmlLineInfo,
  1905. "Invalid encoding declaration inside text declaration.");
  1906. ReadChar ();
  1907. SkipWhitespace ();
  1908. break;
  1909. default:
  1910. throw new XmlException (this as IXmlLineInfo,
  1911. "Invalid encoding declaration inside text declaration.");
  1912. }
  1913. // Encoding value should be checked inside XmlInputStream.
  1914. }
  1915. else
  1916. throw new XmlException (this as IXmlLineInfo,
  1917. "Encoding declaration is mandatory in text declaration.");
  1918. Expect ("?>");
  1919. }
  1920. // The reader is positioned on the first character after
  1921. // the leading '<!'.
  1922. private void ReadDeclaration ()
  1923. {
  1924. int ch = PeekChar ();
  1925. switch (ch)
  1926. {
  1927. case '-':
  1928. Expect ("--");
  1929. ReadComment ();
  1930. break;
  1931. case '[':
  1932. ReadChar ();
  1933. Expect ("CDATA[");
  1934. ReadCDATA ();
  1935. break;
  1936. case 'D':
  1937. Expect ("DOCTYPE");
  1938. ReadDoctypeDecl ();
  1939. break;
  1940. default:
  1941. throw new XmlException (this as IXmlLineInfo,
  1942. "Unexpected declaration markup was found.");
  1943. }
  1944. }
  1945. // The reader is positioned on the first character after
  1946. // the leading '<!--'.
  1947. private void ReadComment ()
  1948. {
  1949. if (currentState == XmlNodeType.None)
  1950. currentState = XmlNodeType.XmlDeclaration;
  1951. ClearValueBuffer ();
  1952. while (PeekChar () != -1) {
  1953. int ch = ReadChar ();
  1954. if (ch == '-' && PeekChar () == '-') {
  1955. ReadChar ();
  1956. if (PeekChar () != '>')
  1957. throw new XmlException (this as IXmlLineInfo,"comments cannot contain '--'");
  1958. ReadChar ();
  1959. break;
  1960. }
  1961. if (XmlChar.IsInvalid (ch))
  1962. throw new XmlException (this as IXmlLineInfo,
  1963. "Not allowed character was found.");
  1964. AppendValueChar (ch);
  1965. }
  1966. SetProperties (
  1967. XmlNodeType.Comment, // nodeType
  1968. String.Empty, // name
  1969. false, // isEmptyElement
  1970. null, // value: create only when required
  1971. true // clearAttributes
  1972. );
  1973. }
  1974. // The reader is positioned on the first character after
  1975. // the leading '<![CDATA['.
  1976. private void ReadCDATA ()
  1977. {
  1978. if (currentState != XmlNodeType.Element)
  1979. throw new XmlException (this as IXmlLineInfo,
  1980. "CDATA section cannot appear in this state.");
  1981. ClearValueBuffer ();
  1982. bool skip = false;
  1983. int ch = 0;
  1984. while (PeekChar () != -1) {
  1985. if (!skip)
  1986. ch = ReadChar ();
  1987. skip = false;
  1988. if (ch == ']' && PeekChar () == ']') {
  1989. ch = ReadChar (); // ']'
  1990. if (PeekChar () == '>') {
  1991. ReadChar (); // '>'
  1992. break;
  1993. } else {
  1994. skip = true;
  1995. }
  1996. }
  1997. if (normalization && ch == '\r') {
  1998. ch = PeekChar ();
  1999. if (ch != '\n')
  2000. // append '\n' instead of '\r'.
  2001. AppendValueChar ('\n');
  2002. // otherwise, discard '\r'.
  2003. continue;
  2004. }
  2005. if (CharacterChecking && XmlChar.IsInvalid (ch))
  2006. throw new XmlException (this, "Invalid character was found.");
  2007. AppendValueChar (ch);
  2008. }
  2009. SetProperties (
  2010. XmlNodeType.CDATA, // nodeType
  2011. String.Empty, // name
  2012. false, // isEmptyElement
  2013. null, // value: create only when required
  2014. true // clearAttributes
  2015. );
  2016. }
  2017. // The reader is positioned on the first character after
  2018. // the leading '<!DOCTYPE'.
  2019. private void ReadDoctypeDecl ()
  2020. {
  2021. if (prohibitDtd)
  2022. throw new XmlException (this as IXmlLineInfo,
  2023. "Document Type Declaration (DTD) is prohibited in this XML.");
  2024. switch (currentState) {
  2025. case XmlNodeType.DocumentType:
  2026. case XmlNodeType.Element:
  2027. case XmlNodeType.EndElement:
  2028. throw new XmlException (this as IXmlLineInfo,
  2029. "Document type cannot appear in this state.");
  2030. }
  2031. currentState = XmlNodeType.DocumentType;
  2032. string doctypeName = null;
  2033. string publicId = null;
  2034. string systemId = null;
  2035. int intSubsetStartLine = 0;
  2036. int intSubsetStartColumn = 0;
  2037. SkipWhitespace ();
  2038. doctypeName = ReadName ();
  2039. SkipWhitespace ();
  2040. switch(PeekChar ())
  2041. {
  2042. case 'S':
  2043. systemId = ReadSystemLiteral (true);
  2044. break;
  2045. case 'P':
  2046. publicId = ReadPubidLiteral ();
  2047. if (!SkipWhitespace ())
  2048. throw new XmlException (this as IXmlLineInfo,
  2049. "Whitespace is required between PUBLIC id and SYSTEM id.");
  2050. systemId = ReadSystemLiteral (false);
  2051. break;
  2052. }
  2053. SkipWhitespace ();
  2054. if(PeekChar () == '[')
  2055. {
  2056. // read markupdecl etc. or end of decl
  2057. ReadChar ();
  2058. intSubsetStartLine = this.LineNumber;
  2059. intSubsetStartColumn = this.LinePosition;
  2060. int startPos = currentTagLength;
  2061. ReadInternalSubset ();
  2062. int endPos = currentTagLength - 1;
  2063. parserContext.InternalSubset = new string (currentTagBuffer, startPos, endPos - startPos);
  2064. }
  2065. // end of DOCTYPE decl.
  2066. ExpectAfterWhitespace ('>');
  2067. GenerateDTDObjectModel (doctypeName, publicId,
  2068. systemId, parserContext.InternalSubset,
  2069. intSubsetStartLine, intSubsetStartColumn);
  2070. // set properties for <!DOCTYPE> node
  2071. SetProperties (
  2072. XmlNodeType.DocumentType, // nodeType
  2073. doctypeName, // name
  2074. false, // isEmptyElement
  2075. parserContext.InternalSubset, // value
  2076. true // clearAttributes
  2077. );
  2078. if (publicId != null)
  2079. AddAttribute ("PUBLIC", publicId);
  2080. if (systemId != null)
  2081. AddAttribute ("SYSTEM", systemId);
  2082. currentAttribute = currentAttributeValue = -1;
  2083. }
  2084. internal DTDObjectModel GenerateDTDObjectModel (string name, string publicId,
  2085. string systemId, string internalSubset)
  2086. {
  2087. return GenerateDTDObjectModel (name, publicId, systemId, internalSubset, 0, 0);
  2088. }
  2089. internal DTDObjectModel GenerateDTDObjectModel (string name, string publicId,
  2090. string systemId, string internalSubset, int intSubsetStartLine, int intSubsetStartColumn)
  2091. {
  2092. // now compile DTD
  2093. parserContext.Dtd = new DTDObjectModel (this.NameTable); // merges both internal and external subsets in the meantime,
  2094. DTD.BaseURI = BaseURI;
  2095. DTD.Name = name;
  2096. DTD.PublicId = publicId;
  2097. DTD.SystemId = systemId;
  2098. DTD.InternalSubset = internalSubset;
  2099. DTD.XmlResolver = resolver;
  2100. DTD.IsStandalone = isStandalone;
  2101. DTD.LineNumber = line;
  2102. DTD.LinePosition = column;
  2103. DTDReader dr = new DTDReader (DTD, intSubsetStartLine, intSubsetStartColumn);
  2104. dr.Normalization = this.normalization;
  2105. #if DTD_HANDLE_EVENTS
  2106. dr.ValidationEventHandler += new ValidationEventHandler (OnValidationEvent);
  2107. #endif
  2108. return dr.GenerateDTDObjectModel ();
  2109. }
  2110. private void OnValidationEvent (object o, ValidationEventArgs e)
  2111. {
  2112. #if DTD_HANDLE_EVENTS
  2113. if (ValidationEventHandler != null)
  2114. // Override object as this.
  2115. ValidationEventHandler (this, e);
  2116. #endif
  2117. }
  2118. private enum DtdInputState
  2119. {
  2120. Free = 1,
  2121. ElementDecl,
  2122. AttlistDecl,
  2123. EntityDecl,
  2124. NotationDecl,
  2125. PI,
  2126. Comment,
  2127. InsideSingleQuoted,
  2128. InsideDoubleQuoted,
  2129. }
  2130. private class DtdInputStateStack
  2131. {
  2132. Stack intern = new Stack ();
  2133. public DtdInputStateStack ()
  2134. {
  2135. Push (DtdInputState.Free);
  2136. }
  2137. public DtdInputState Peek ()
  2138. {
  2139. return (DtdInputState) intern.Peek ();
  2140. }
  2141. public DtdInputState Pop ()
  2142. {
  2143. return (DtdInputState) intern.Pop ();
  2144. }
  2145. public void Push (DtdInputState val)
  2146. {
  2147. intern.Push (val);
  2148. }
  2149. }
  2150. DtdInputStateStack stateStack = new DtdInputStateStack ();
  2151. DtdInputState State {
  2152. get { return stateStack.Peek (); }
  2153. }
  2154. // Simply read but not generate any result.
  2155. private void ReadInternalSubset ()
  2156. {
  2157. bool continueParse = true;
  2158. while (continueParse) {
  2159. switch (ReadChar ()) {
  2160. case ']':
  2161. switch (State) {
  2162. case DtdInputState.Free:
  2163. continueParse = false;
  2164. break;
  2165. case DtdInputState.InsideDoubleQuoted:
  2166. continue;
  2167. case DtdInputState.InsideSingleQuoted:
  2168. continue;
  2169. default:
  2170. throw new XmlException (this as IXmlLineInfo,"unexpected end of file at DTD.");
  2171. }
  2172. break;
  2173. case -1:
  2174. throw new XmlException (this as IXmlLineInfo,"unexpected end of file at DTD.");
  2175. case '<':
  2176. switch (State) {
  2177. case DtdInputState.InsideDoubleQuoted:
  2178. case DtdInputState.InsideSingleQuoted:
  2179. case DtdInputState.Comment:
  2180. continue; // well-formed
  2181. }
  2182. int c = ReadChar ();
  2183. switch (c) {
  2184. case '?':
  2185. stateStack.Push (DtdInputState.PI);
  2186. break;
  2187. case '!':
  2188. switch (ReadChar ()) {
  2189. case 'E':
  2190. switch (ReadChar ()) {
  2191. case 'L':
  2192. Expect ("EMENT");
  2193. stateStack.Push (DtdInputState.ElementDecl);
  2194. break;
  2195. case 'N':
  2196. Expect ("TITY");
  2197. stateStack.Push (DtdInputState.EntityDecl);
  2198. break;
  2199. default:
  2200. throw new XmlException (this as IXmlLineInfo,"unexpected token '<!E'.");
  2201. }
  2202. break;
  2203. case 'A':
  2204. Expect ("TTLIST");
  2205. stateStack.Push (DtdInputState.AttlistDecl);
  2206. break;
  2207. case 'N':
  2208. Expect ("OTATION");
  2209. stateStack.Push (DtdInputState.NotationDecl);
  2210. break;
  2211. case '-':
  2212. Expect ("-");
  2213. stateStack.Push (DtdInputState.Comment);
  2214. break;
  2215. }
  2216. break;
  2217. default:
  2218. throw new XmlException (this as IXmlLineInfo, String.Format ("unexpected '<{0}'.", (char) c));
  2219. }
  2220. break;
  2221. case '\'':
  2222. if (State == DtdInputState.InsideSingleQuoted)
  2223. stateStack.Pop ();
  2224. else if (State != DtdInputState.InsideDoubleQuoted && State != DtdInputState.Comment)
  2225. stateStack.Push (DtdInputState.InsideSingleQuoted);
  2226. break;
  2227. case '"':
  2228. if (State == DtdInputState.InsideDoubleQuoted)
  2229. stateStack.Pop ();
  2230. else if (State != DtdInputState.InsideSingleQuoted && State != DtdInputState.Comment)
  2231. stateStack.Push (DtdInputState.InsideDoubleQuoted);
  2232. break;
  2233. case '>':
  2234. switch (State) {
  2235. case DtdInputState.ElementDecl:
  2236. goto case DtdInputState.NotationDecl;
  2237. case DtdInputState.AttlistDecl:
  2238. goto case DtdInputState.NotationDecl;
  2239. case DtdInputState.EntityDecl:
  2240. goto case DtdInputState.NotationDecl;
  2241. case DtdInputState.NotationDecl:
  2242. stateStack.Pop ();
  2243. break;
  2244. case DtdInputState.InsideDoubleQuoted:
  2245. case DtdInputState.InsideSingleQuoted:
  2246. case DtdInputState.Comment:
  2247. continue;
  2248. default:
  2249. throw new XmlException (this as IXmlLineInfo,"unexpected token '>'");
  2250. }
  2251. break;
  2252. case '?':
  2253. if (State == DtdInputState.PI) {
  2254. if (ReadChar () == '>')
  2255. stateStack.Pop ();
  2256. }
  2257. break;
  2258. case '-':
  2259. if (State == DtdInputState.Comment) {
  2260. if (PeekChar () == '-') {
  2261. ReadChar ();
  2262. Expect ('>');
  2263. stateStack.Pop ();
  2264. }
  2265. }
  2266. break;
  2267. case '%':
  2268. if (State != DtdInputState.Free && State != DtdInputState.EntityDecl && State != DtdInputState.Comment && State != DtdInputState.InsideDoubleQuoted && State != DtdInputState.InsideSingleQuoted)
  2269. throw new XmlException (this as IXmlLineInfo,"Parameter Entity Reference cannot appear as a part of markupdecl (see XML spec 2.8).");
  2270. break;
  2271. }
  2272. }
  2273. }
  2274. // The reader is positioned on the first 'S' of "SYSTEM".
  2275. private string ReadSystemLiteral (bool expectSYSTEM)
  2276. {
  2277. if(expectSYSTEM) {
  2278. Expect ("SYSTEM");
  2279. if (!SkipWhitespace ())
  2280. throw new XmlException (this as IXmlLineInfo,
  2281. "Whitespace is required after 'SYSTEM'.");
  2282. }
  2283. else
  2284. SkipWhitespace ();
  2285. int quoteChar = ReadChar (); // apos or quot
  2286. int startPos = currentTagLength;
  2287. int c = 0;
  2288. ClearValueBuffer ();
  2289. while (c != quoteChar) {
  2290. c = ReadChar ();
  2291. if (c < 0)
  2292. throw new XmlException (this as IXmlLineInfo,"Unexpected end of stream in ExternalID.");
  2293. if (c != quoteChar)
  2294. AppendValueChar (c);
  2295. }
  2296. return CreateValueString ();
  2297. }
  2298. private string ReadPubidLiteral()
  2299. {
  2300. Expect ("PUBLIC");
  2301. if (!SkipWhitespace ())
  2302. throw new XmlException (this as IXmlLineInfo,
  2303. "Whitespace is required after 'PUBLIC'.");
  2304. int quoteChar = ReadChar ();
  2305. int startPos = currentTagLength;
  2306. int c = 0;
  2307. ClearValueBuffer ();
  2308. while(c != quoteChar)
  2309. {
  2310. c = ReadChar ();
  2311. if(c < 0) throw new XmlException (this as IXmlLineInfo,"Unexpected end of stream in ExternalID.");
  2312. if(c != quoteChar && !XmlChar.IsPubidChar (c))
  2313. throw new XmlException (this as IXmlLineInfo,"character '" + (char) c + "' not allowed for PUBLIC ID");
  2314. if (c != quoteChar)
  2315. AppendValueChar (c);
  2316. }
  2317. return CreateValueString ();
  2318. }
  2319. // The reader is positioned on the first character
  2320. // of the name.
  2321. private string ReadName ()
  2322. {
  2323. int ch = PeekChar ();
  2324. if (!XmlChar.IsFirstNameChar (ch))
  2325. throw new XmlException (this as IXmlLineInfo,String.Format (CultureInfo.InvariantCulture, "a name did not start with a legal character {0} ({1})", ch, (char) ch));
  2326. nameLength = 0;
  2327. AppendNameChar (ReadChar ());
  2328. while (XmlChar.IsNameChar (PeekChar ())) {
  2329. AppendNameChar (ReadChar ());
  2330. }
  2331. return parserContext.NameTable.Add (nameBuffer, 0, nameLength);
  2332. }
  2333. // Read the next character and compare it against the
  2334. // specified character.
  2335. private void Expect (int expected)
  2336. {
  2337. int ch = ReadChar ();
  2338. if (ch != expected) {
  2339. throw new XmlException (this as IXmlLineInfo,
  2340. String.Format (CultureInfo.InvariantCulture,
  2341. "expected '{0}' ({1:X}) but found '{2}' ({3:X})",
  2342. (char) expected,
  2343. expected,
  2344. (char) ch,
  2345. ch));
  2346. }
  2347. }
  2348. private void Expect (string expected)
  2349. {
  2350. int len = expected.Length;
  2351. for(int i=0; i< len; i++)
  2352. Expect (expected[i]);
  2353. }
  2354. private void ExpectAfterWhitespace (char c)
  2355. {
  2356. while (true) {
  2357. int i = ReadChar ();
  2358. if (i < 0x21 && XmlChar.IsWhitespace (i))
  2359. continue;
  2360. if (c != i)
  2361. throw new XmlException (this, String.Format (CultureInfo.InvariantCulture, "Expected {0}, but found {1} [{2}]", c, (char) i, i));
  2362. break;
  2363. }
  2364. }
  2365. // Does not consume the first non-whitespace character.
  2366. private bool SkipWhitespace ()
  2367. {
  2368. bool skipped = XmlChar.IsWhitespace (PeekChar ());
  2369. if (!skipped)
  2370. return false;
  2371. while (XmlChar.IsWhitespace (PeekChar ()))
  2372. ReadChar ();
  2373. return skipped;
  2374. }
  2375. private void ReadWhitespace ()
  2376. {
  2377. if (currentState == XmlNodeType.None)
  2378. currentState = XmlNodeType.XmlDeclaration;
  2379. ClearValueBuffer ();
  2380. int ch = PeekChar ();
  2381. do {
  2382. AppendValueChar (ReadChar ());
  2383. } while ((ch = PeekChar ()) != -1 && XmlChar.IsWhitespace (ch));
  2384. if (currentState == XmlNodeType.Element && ch != -1 && ch != '<')
  2385. ReadText (false);
  2386. else {
  2387. XmlNodeType nodeType = (this.XmlSpace == XmlSpace.Preserve) ?
  2388. XmlNodeType.SignificantWhitespace : XmlNodeType.Whitespace;
  2389. SetProperties (nodeType,
  2390. String.Empty,
  2391. false,
  2392. null, // value: create only when required
  2393. true);
  2394. }
  2395. return;
  2396. }
  2397. // Since ReadBase64() is processed for every 4 chars, it does
  2398. // not handle '=' here.
  2399. private byte GetBase64Byte (char ch)
  2400. {
  2401. switch (ch) {
  2402. case '+':
  2403. return 62;
  2404. case '/':
  2405. return 63;
  2406. default:
  2407. if (ch >= 'A' && ch <= 'Z')
  2408. return (byte) (ch - 'A');
  2409. else if (ch >= 'a' && ch <= 'z')
  2410. return (byte) (ch - 'a' + 26);
  2411. else if (ch >= '0' && ch <= '9')
  2412. return (byte) (ch - '0' + 52);
  2413. else
  2414. throw new XmlException ("Invalid Base64 character was found.");
  2415. }
  2416. }
  2417. // Returns -1 if it should throw an error.
  2418. private int ReadCharsInternal (char [] buffer, int offset, int length)
  2419. {
  2420. if (IsEmptyElement) {
  2421. Read ();
  2422. return 0;
  2423. }
  2424. if (offset < 0)
  2425. throw new ArgumentOutOfRangeException ("offset", offset, "Offset must be non-negative integer.");
  2426. else if (length < 0)
  2427. throw new ArgumentOutOfRangeException ("length", length, "Length must be non-negative integer.");
  2428. else if (buffer.Length < offset + length)
  2429. throw new ArgumentOutOfRangeException ("buffer length is smaller than the sum of offset and length.");
  2430. if (NodeType != XmlNodeType.Element)
  2431. return 0;
  2432. shouldSkipUntilEndTag = true;
  2433. int bufIndex = offset;
  2434. for (int i = 0; i < length; i++) {
  2435. int c = PeekChar ();
  2436. switch (c) {
  2437. case -1:
  2438. throw new XmlException (this as IXmlLineInfo, "Unexpected end of xml.");
  2439. case '<':
  2440. ReadChar ();
  2441. if (PeekChar () != '/') {
  2442. buffer [bufIndex++] = '<';
  2443. continue;
  2444. }
  2445. // Seems to skip immediate EndElement
  2446. Expect ('/');
  2447. if (depthUp) {
  2448. depth++;
  2449. depthUp = false;
  2450. }
  2451. ReadEndTag ();
  2452. shouldSkipUntilEndTag = false;
  2453. Read (); // move to the next node
  2454. return i;
  2455. default:
  2456. ReadChar ();
  2457. if (c < Char.MaxValue)
  2458. buffer [bufIndex++] = (char) c;
  2459. else {
  2460. buffer [bufIndex++] = (char) (c / 0x10000 + 0xD800 - 1);
  2461. buffer [bufIndex++] = (char) (c % 0x10000 + 0xDC00);
  2462. }
  2463. break;
  2464. }
  2465. }
  2466. return length;
  2467. }
  2468. private bool ReadUntilEndTag ()
  2469. {
  2470. int ch;
  2471. do {
  2472. ch = ReadChar ();
  2473. switch (ch) {
  2474. case -1:
  2475. throw new XmlException (this as IXmlLineInfo,
  2476. "Unexpected end of xml.");
  2477. case '<':
  2478. if (PeekChar () != '/')
  2479. continue;
  2480. ReadChar ();
  2481. string name = ReadName ();
  2482. if (name != elementNames [elementNameStackPos - 1])
  2483. continue;
  2484. Expect ('>');
  2485. depth--;
  2486. elementNames [--elementNameStackPos] = null;
  2487. return Read ();
  2488. }
  2489. } while (true);
  2490. }
  2491. #endregion
  2492. }
  2493. }