XmlTextReader.cs 71 KB

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