XmlTextReader.cs 70 KB

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