XmlTextReader.cs 71 KB

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