XmlTextReader.cs 77 KB

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