XmlTextReader.cs 73 KB

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