XmlTextReader.cs 70 KB

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