XmlTextReader.cs 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707
  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 ())
  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 ())
  926. //FIXME: copy MS.NET behaviour when unpaired surrogate found
  927. return peekChars [peekCharsIndex];
  928. return PeekChar ();
  929. }
  930. char highhalfChar = peekChars [peekCharsIndex];
  931. char lowhalfChar = peekChars [peekCharsIndex+1];
  932. if (((highhalfChar & 0xFC00) != 0xD800) || ((lowhalfChar & 0xFC00) != 0xDC00))
  933. //FIXME: copy MS.NET behaviour when unpaired surrogate found
  934. return highhalfChar;
  935. return 0x10000 + (highhalfChar-0xD800)*0x400 + (lowhalfChar-0xDC00);
  936. }
  937. private int ReadChar ()
  938. {
  939. int ch = PeekChar ();
  940. peekCharsIndex++;
  941. if (ch >= 0x10000)
  942. peekCharsIndex++; //Increment by 2 when a compound UCS-4 character was found
  943. if (ch == '\n') {
  944. line++;
  945. column = 1;
  946. } else if (ch == -1) {
  947. return -1;
  948. } else {
  949. column++;
  950. }
  951. if (currentState != XmlNodeType.Element)
  952. AppendCurrentTagChar (ch);
  953. return ch;
  954. }
  955. private bool ReadTextReader ()
  956. {
  957. peekCharsIndex = 0;
  958. peekCharsLength = reader.Read (peekChars, 0, peekCharCapacity);
  959. return (peekCharsLength != 0);
  960. }
  961. private bool ReadContent ()
  962. {
  963. currentTagLength = 0;
  964. if (popScope) {
  965. parserContext.NamespaceManager.PopScope ();
  966. parserContext.PopScope ();
  967. popScope = false;
  968. }
  969. if (returnEntityReference)
  970. SetEntityReferenceProperties ();
  971. else {
  972. int c = PeekChar ();
  973. if (c == -1) {
  974. readState = ReadState.EndOfFile;
  975. ClearValueBuffer ();
  976. SetProperties (
  977. XmlNodeType.None, // nodeType
  978. String.Empty, // name
  979. String.Empty, // prefix
  980. String.Empty, // localName
  981. false, // isEmptyElement
  982. null, // value
  983. true // clearAttributes
  984. );
  985. if (depth > 0)
  986. throw NotWFError ("unexpected end of file. Current depth is " + depth);
  987. return false;
  988. } else {
  989. switch (c) {
  990. case '<':
  991. ReadChar ();
  992. switch (PeekChar ())
  993. {
  994. case '/':
  995. ReadChar ();
  996. ReadEndTag ();
  997. break;
  998. case '?':
  999. ReadChar ();
  1000. ReadProcessingInstruction ();
  1001. break;
  1002. case '!':
  1003. ReadChar ();
  1004. ReadDeclaration ();
  1005. break;
  1006. default:
  1007. ReadStartTag ();
  1008. break;
  1009. }
  1010. break;
  1011. case '\r':
  1012. case '\n':
  1013. case '\t':
  1014. case ' ':
  1015. if (whitespaceHandling == WhitespaceHandling.All ||
  1016. whitespaceHandling == WhitespaceHandling.Significant)
  1017. ReadWhitespace ();
  1018. else {
  1019. SkipWhitespace ();
  1020. return ReadContent ();
  1021. }
  1022. break;
  1023. default:
  1024. ReadText (true);
  1025. break;
  1026. }
  1027. }
  1028. }
  1029. return this.ReadState != ReadState.EndOfFile;
  1030. }
  1031. private void SetEntityReferenceProperties ()
  1032. {
  1033. DTDEntityDeclaration decl = DTD != null ? DTD.EntityDecls [entityReferenceName] : null;
  1034. if (this.isStandalone)
  1035. if (DTD == null || decl == null || !decl.IsInternalSubset)
  1036. throw NotWFError ("Standalone document must not contain any references to an non-internally declared entity.");
  1037. if (decl != null && decl.NotationName != null)
  1038. throw NotWFError ("Reference to any unparsed entities is not allowed here.");
  1039. ClearValueBuffer ();
  1040. SetProperties (
  1041. XmlNodeType.EntityReference, // nodeType
  1042. entityReferenceName, // name
  1043. String.Empty, // prefix
  1044. entityReferenceName, // localName
  1045. false, // isEmptyElement
  1046. null, // value
  1047. true // clearAttributes
  1048. );
  1049. returnEntityReference = false;
  1050. entityReferenceName = String.Empty;
  1051. }
  1052. // The leading '<' has already been consumed.
  1053. private void ReadStartTag ()
  1054. {
  1055. if (currentState == XmlNodeType.EndElement)
  1056. throw NotWFError ("Multiple document element was detected.");
  1057. currentState = XmlNodeType.Element;
  1058. parserContext.NamespaceManager.PushScope ();
  1059. currentLinkedNodeLineNumber = line;
  1060. currentLinkedNodeLinePosition = column;
  1061. string prefix, localName;
  1062. string name = ReadName (out prefix, out localName);
  1063. if (currentState == XmlNodeType.EndElement)
  1064. throw NotWFError ("document has terminated, cannot open new element");
  1065. bool isEmptyElement = false;
  1066. ClearAttributes ();
  1067. SkipWhitespace ();
  1068. if (XmlChar.IsFirstNameChar (PeekChar ()))
  1069. ReadAttributes (false);
  1070. cursorToken = this.currentToken;
  1071. // fill namespaces
  1072. for (int i = 0; i < attributeCount; i++)
  1073. attributeTokens [i].FillXmlns ();
  1074. for (int i = 0; i < attributeCount; i++)
  1075. attributeTokens [i].FillNamespace ();
  1076. // quick name check
  1077. for (int i = 0; i < attributeCount; i++) {
  1078. for (int j = i + 1; j < attributeCount; j++)
  1079. if (Object.ReferenceEquals (attributeTokens [i].Name, attributeTokens [j].Name) ||
  1080. (Object.ReferenceEquals (attributeTokens [i].LocalName, attributeTokens [j].LocalName) &&
  1081. Object.ReferenceEquals (attributeTokens [i].NamespaceURI, attributeTokens [j].NamespaceURI)))
  1082. throw NotWFError ("Attribute name and qualified name must be identical.");
  1083. }
  1084. if (PeekChar () == '/') {
  1085. ReadChar ();
  1086. isEmptyElement = true;
  1087. popScope = true;
  1088. }
  1089. else {
  1090. depthUp = true;
  1091. PushElementName (name);
  1092. }
  1093. parserContext.PushScope ();
  1094. Expect ('>');
  1095. SetProperties (
  1096. XmlNodeType.Element, // nodeType
  1097. name, // name
  1098. prefix, // prefix
  1099. localName, // name
  1100. isEmptyElement, // isEmptyElement
  1101. null, // value
  1102. false // clearAttributes
  1103. );
  1104. if (prefix.Length > 0)
  1105. currentToken.NamespaceURI = LookupNamespace (prefix, true);
  1106. else if (namespaces)
  1107. currentToken.NamespaceURI = parserContext.NamespaceManager.DefaultNamespace;
  1108. if (namespaces) {
  1109. if (NamespaceURI == null)
  1110. throw NotWFError (String.Format ("'{0}' is undeclared namespace.", Prefix));
  1111. try {
  1112. for (int i = 0; i < attributeCount; i++) {
  1113. MoveToAttribute (i);
  1114. if (NamespaceURI == null)
  1115. throw NotWFError (String.Format ("'{0}' is undeclared namespace.", Prefix));
  1116. }
  1117. } finally {
  1118. MoveToElement ();
  1119. }
  1120. }
  1121. for (int i = 0; i < attributeCount; i++) {
  1122. if (!Object.ReferenceEquals (attributeTokens [i].Prefix, XmlNamespaceManager.PrefixXml))
  1123. continue;
  1124. string aname = attributeTokens [i].LocalName;
  1125. string value = attributeTokens [i].Value;
  1126. switch (aname) {
  1127. case "base":
  1128. if (this.resolver != null) {
  1129. Uri buri =
  1130. BaseURI != String.Empty ?
  1131. new Uri (BaseURI) : null;
  1132. Uri uri = resolver.ResolveUri (
  1133. buri, value);
  1134. parserContext.BaseURI =
  1135. uri != null ?
  1136. uri.ToString () :
  1137. String.Empty;
  1138. }
  1139. else
  1140. parserContext.BaseURI = value;
  1141. break;
  1142. case "lang":
  1143. parserContext.XmlLang = value;
  1144. break;
  1145. case "space":
  1146. switch (value) {
  1147. case "preserve":
  1148. parserContext.XmlSpace = XmlSpace.Preserve;
  1149. break;
  1150. case "default":
  1151. parserContext.XmlSpace = XmlSpace.Default;
  1152. break;
  1153. default:
  1154. throw NotWFError (String.Format ("Invalid xml:space value: {0}", value));
  1155. }
  1156. break;
  1157. }
  1158. }
  1159. if (IsEmptyElement)
  1160. CheckCurrentStateUpdate ();
  1161. }
  1162. private void PushElementName (string name)
  1163. {
  1164. if (elementNames.Length == elementNameStackPos) {
  1165. string [] newArray = new string [elementNames.Length * 2];
  1166. Array.Copy (elementNames, 0, newArray, 0, elementNameStackPos);
  1167. elementNames = newArray;
  1168. }
  1169. elementNames [elementNameStackPos++] = name;
  1170. }
  1171. // The reader is positioned on the first character
  1172. // of the element's name.
  1173. private void ReadEndTag ()
  1174. {
  1175. if (currentState != XmlNodeType.Element)
  1176. throw NotWFError ("End tag cannot appear in this state.");
  1177. currentLinkedNodeLineNumber = line;
  1178. currentLinkedNodeLinePosition = column;
  1179. string prefix, localName;
  1180. string name = ReadName (out prefix, out localName);
  1181. if (elementNameStackPos == 0)
  1182. throw NotWFError ("closing element without matching opening element");
  1183. string expected = elementNames [--elementNameStackPos];
  1184. if (expected != name)
  1185. throw NotWFError (String.Format ("unmatched closing element: expected {0} but found {1}", expected, name));
  1186. ExpectAfterWhitespace ('>');
  1187. --depth;
  1188. SetProperties (
  1189. XmlNodeType.EndElement, // nodeType
  1190. name, // name
  1191. prefix, // prefix
  1192. localName, // localName
  1193. false, // isEmptyElement
  1194. null, // value
  1195. true // clearAttributes
  1196. );
  1197. if (prefix.Length > 0)
  1198. currentToken.NamespaceURI = LookupNamespace (prefix, true);
  1199. else if (namespaces)
  1200. currentToken.NamespaceURI = parserContext.NamespaceManager.DefaultNamespace;
  1201. popScope = true;
  1202. CheckCurrentStateUpdate ();
  1203. }
  1204. private void CheckCurrentStateUpdate ()
  1205. {
  1206. if (depth == 0 && !allowMultipleRoot && (IsEmptyElement || NodeType == XmlNodeType.EndElement))
  1207. currentState = XmlNodeType.EndElement;
  1208. }
  1209. private void AppendSurrogatePairNameChar (int ch)
  1210. {
  1211. nameBuffer [nameLength++] = (char) (ch / 0x10000 + 0xD800 - 1);
  1212. if (nameLength == nameCapacity)
  1213. ExpandNameCapacity ();
  1214. nameBuffer [nameLength++] = (char) (ch % 0x10000 + 0xDC00);
  1215. }
  1216. private void ExpandNameCapacity ()
  1217. {
  1218. nameCapacity = nameCapacity * 2;
  1219. char [] oldNameBuffer = nameBuffer;
  1220. nameBuffer = new char [nameCapacity];
  1221. Array.Copy (oldNameBuffer, nameBuffer, nameLength);
  1222. }
  1223. private void AppendValueChar (int ch)
  1224. {
  1225. if (ch < Char.MaxValue)
  1226. valueBuffer.Append ((char) ch);
  1227. else
  1228. AppendSurrogatePairValueChar (ch);
  1229. }
  1230. private void AppendSurrogatePairValueChar (int ch)
  1231. {
  1232. valueBuffer.Append ((char) (ch / 0x10000 + 0xD800 - 1));
  1233. valueBuffer.Append ((char) (ch % 0x10000 + 0xDC00));
  1234. }
  1235. private string CreateValueString ()
  1236. {
  1237. return (valueBuffer.Capacity < 100) ?
  1238. valueBuffer.ToString (0, valueBuffer.Length) :
  1239. valueBuffer.ToString ();
  1240. }
  1241. private void ClearValueBuffer ()
  1242. {
  1243. valueBuffer.Length = 0;
  1244. }
  1245. private void AppendCurrentTagChar (int ch)
  1246. {
  1247. if (currentTagLength == currentTagCapacity)
  1248. ExpandCurrentTagCapacity ();
  1249. if (ch < Char.MaxValue)
  1250. currentTagBuffer [currentTagLength++] = (char) ch;
  1251. else {
  1252. currentTagBuffer [currentTagLength++] = (char) (ch / 0x10000 + 0xD800 - 1);
  1253. if (currentTagLength == currentTagCapacity)
  1254. ExpandCurrentTagCapacity ();
  1255. currentTagBuffer [currentTagLength++] = (char) (ch % 0x10000 + 0xDC00);
  1256. }
  1257. }
  1258. private void ExpandCurrentTagCapacity ()
  1259. {
  1260. currentTagCapacity = currentTagCapacity * 2;
  1261. char [] oldCurrentTagBuffer = currentTagBuffer;
  1262. currentTagBuffer = new char [currentTagCapacity];
  1263. Array.Copy (oldCurrentTagBuffer, currentTagBuffer, currentTagLength);
  1264. }
  1265. // The reader is positioned on the first character
  1266. // of the text.
  1267. private void ReadText (bool notWhitespace)
  1268. {
  1269. if (currentState != XmlNodeType.Element)
  1270. throw NotWFError ("Text node cannot appear in this state.");
  1271. if (notWhitespace)
  1272. ClearValueBuffer ();
  1273. int ch = PeekChar ();
  1274. bool previousWasCloseBracket = false;
  1275. while (ch != '<' && ch != -1) {
  1276. if (ch == '&') {
  1277. ReadChar ();
  1278. ch = ReadReference (false);
  1279. if (returnEntityReference) // Returns -1 if char validation should not be done
  1280. break;
  1281. } else if (normalization && ch == '\r') {
  1282. ReadChar ();
  1283. ch = ReadChar ();
  1284. if (ch != '\n')
  1285. // append '\n' instead of '\r'.
  1286. AppendValueChar ('\n');
  1287. // and in case of "\r\n", discard '\r'.
  1288. } else {
  1289. if (CharacterChecking && XmlChar.IsInvalid (ch))
  1290. throw NotWFError ("Not allowed character was found.");
  1291. ch = ReadChar ();
  1292. }
  1293. // FIXME: it might be optimized by the JIT later,
  1294. // AppendValueChar (ch);
  1295. {
  1296. if (ch < Char.MaxValue)
  1297. valueBuffer.Append ((char) ch);
  1298. else
  1299. AppendSurrogatePairValueChar (ch);
  1300. }
  1301. // Block "]]>"
  1302. if (ch == ']') {
  1303. if (previousWasCloseBracket)
  1304. if (PeekChar () == '>')
  1305. throw NotWFError ("Inside text content, character sequence ']]>' is not allowed.");
  1306. previousWasCloseBracket = true;
  1307. }
  1308. else if (previousWasCloseBracket)
  1309. previousWasCloseBracket = false;
  1310. ch = PeekChar ();
  1311. notWhitespace = true;
  1312. }
  1313. if (returnEntityReference && valueBuffer.Length == 0) {
  1314. SetEntityReferenceProperties ();
  1315. } else {
  1316. XmlNodeType nodeType = notWhitespace ? XmlNodeType.Text :
  1317. this.XmlSpace == XmlSpace.Preserve ? XmlNodeType.SignificantWhitespace : XmlNodeType.Whitespace;
  1318. SetProperties (
  1319. nodeType, // nodeType
  1320. String.Empty, // name
  1321. String.Empty, // prefix
  1322. String.Empty, // localName
  1323. false, // isEmptyElement
  1324. null, // value: create only when required
  1325. true // clearAttributes
  1326. );
  1327. }
  1328. }
  1329. // The leading '&' has already been consumed.
  1330. // Returns true if the entity reference isn't a simple
  1331. // character reference or one of the predefined entities.
  1332. // This allows the ReadText method to break so that the
  1333. // next call to Read will return the EntityReference node.
  1334. private int ReadReference (bool ignoreEntityReferences)
  1335. {
  1336. if (PeekChar () == '#') {
  1337. ReadChar ();
  1338. return ReadCharacterReference ();
  1339. } else
  1340. return ReadEntityReference (ignoreEntityReferences);
  1341. }
  1342. private int ReadCharacterReference ()
  1343. {
  1344. int value = 0;
  1345. if (PeekChar () == 'x') {
  1346. ReadChar ();
  1347. while (PeekChar () != ';' && PeekChar () != -1) {
  1348. int ch = ReadChar ();
  1349. if (ch >= '0' && ch <= '9')
  1350. value = (value << 4) + ch - '0';
  1351. else if (ch >= 'A' && ch <= 'F')
  1352. value = (value << 4) + ch - 'A' + 10;
  1353. else if (ch >= 'a' && ch <= 'f')
  1354. value = (value << 4) + ch - 'a' + 10;
  1355. else
  1356. throw NotWFError (String.Format (CultureInfo.InvariantCulture,
  1357. "invalid hexadecimal digit: {0} (#x{1:X})",
  1358. (char) ch,
  1359. ch));
  1360. }
  1361. } else {
  1362. while (PeekChar () != ';' && PeekChar () != -1) {
  1363. int ch = ReadChar ();
  1364. if (ch >= '0' && ch <= '9')
  1365. value = value * 10 + ch - '0';
  1366. else
  1367. throw NotWFError (String.Format (CultureInfo.InvariantCulture,
  1368. "invalid decimal digit: {0} (#x{1:X})",
  1369. (char) ch,
  1370. ch));
  1371. }
  1372. }
  1373. ReadChar (); // ';'
  1374. // There is no way to save surrogate pairs...
  1375. if (CharacterChecking && Normalization &&
  1376. XmlChar.IsInvalid (value))
  1377. throw NotWFError ("Referenced character was not allowed in XML. Normalization is " + normalization + ", checkCharacters = " + checkCharacters);
  1378. return value;
  1379. }
  1380. // Returns -1 if it should not be validated.
  1381. // Real EOF must not be detected here.
  1382. private int ReadEntityReference (bool ignoreEntityReferences)
  1383. {
  1384. string name = ReadName ();
  1385. Expect (';');
  1386. int predefined = XmlChar.GetPredefinedEntity (name);
  1387. if (predefined >= 0)
  1388. return predefined;
  1389. else {
  1390. if (ignoreEntityReferences) {
  1391. AppendValueChar ('&');
  1392. for (int i = 0; i < name.Length; i++)
  1393. AppendValueChar (name [i]);
  1394. AppendValueChar (';');
  1395. } else {
  1396. returnEntityReference = true;
  1397. entityReferenceName = name;
  1398. }
  1399. }
  1400. return -1;
  1401. }
  1402. // The reader is positioned on the first character of
  1403. // the attribute name.
  1404. private void ReadAttributes (bool isXmlDecl)
  1405. {
  1406. int peekChar = -1;
  1407. bool requireWhitespace = false;
  1408. currentAttribute = -1;
  1409. currentAttributeValue = -1;
  1410. do {
  1411. if (!SkipWhitespace () && requireWhitespace)
  1412. throw NotWFError ("Unexpected token. Name is required here.");
  1413. IncrementAttributeToken ();
  1414. currentAttributeToken.LineNumber = line;
  1415. currentAttributeToken.LinePosition = column;
  1416. string prefix, localName;
  1417. currentAttributeToken.Name = ReadName (out prefix, out localName);
  1418. currentAttributeToken.Prefix = prefix;
  1419. currentAttributeToken.LocalName = localName;
  1420. ExpectAfterWhitespace ('=');
  1421. SkipWhitespace ();
  1422. ReadAttributeValueTokens (-1);
  1423. // This hack is required for xmldecl which has
  1424. // both effective attributes and Value.
  1425. string dummyValue;
  1426. if (isXmlDecl)
  1427. dummyValue = currentAttributeToken.Value;
  1428. attributeCount++;
  1429. if (!SkipWhitespace ())
  1430. requireWhitespace = true;
  1431. peekChar = PeekChar ();
  1432. if (isXmlDecl) {
  1433. if (peekChar == '?')
  1434. break;
  1435. }
  1436. else if (peekChar == '/' || peekChar == '>')
  1437. break;
  1438. } while (peekChar != -1);
  1439. currentAttribute = -1;
  1440. currentAttributeValue = -1;
  1441. }
  1442. private void AddDtdAttribute (string name, string value)
  1443. {
  1444. IncrementAttributeToken ();
  1445. XmlAttributeTokenInfo ati = attributeTokens [currentAttribute];
  1446. ati.Name = parserContext.NameTable.Add (name);
  1447. ati.Prefix = String.Empty;
  1448. ati.NamespaceURI = String.Empty;
  1449. IncrementAttributeValueToken ();
  1450. XmlTokenInfo vti = attributeValueTokens [currentAttributeValue];
  1451. vti.Value = value;
  1452. SetTokenProperties (vti,
  1453. XmlNodeType.Text,
  1454. String.Empty,
  1455. String.Empty,
  1456. String.Empty,
  1457. false,
  1458. value,
  1459. false);
  1460. attributeCount++;
  1461. }
  1462. private void IncrementAttributeToken ()
  1463. {
  1464. currentAttribute++;
  1465. if (attributeTokens.Length == currentAttribute) {
  1466. XmlAttributeTokenInfo [] newArray =
  1467. new XmlAttributeTokenInfo [attributeTokens.Length * 2];
  1468. attributeTokens.CopyTo (newArray, 0);
  1469. attributeTokens = newArray;
  1470. }
  1471. if (attributeTokens [currentAttribute] == null)
  1472. attributeTokens [currentAttribute] = new XmlAttributeTokenInfo (this);
  1473. currentAttributeToken = attributeTokens [currentAttribute];
  1474. currentAttributeToken.Clear ();
  1475. }
  1476. private void IncrementAttributeValueToken ()
  1477. {
  1478. currentAttributeValue++;
  1479. if (attributeValueTokens.Length == currentAttributeValue) {
  1480. XmlTokenInfo [] newArray = new XmlTokenInfo [attributeValueTokens.Length * 2];
  1481. attributeValueTokens.CopyTo (newArray, 0);
  1482. attributeValueTokens = newArray;
  1483. }
  1484. if (attributeValueTokens [currentAttributeValue] == null)
  1485. attributeValueTokens [currentAttributeValue] = new XmlTokenInfo (this);
  1486. currentAttributeValueToken = attributeValueTokens [currentAttributeValue];
  1487. currentAttributeValueToken.Clear ();
  1488. }
  1489. // LAMESPEC: Orthodox XML reader should normalize attribute values
  1490. private void ReadAttributeValueTokens (int dummyQuoteChar)
  1491. {
  1492. int quoteChar = (dummyQuoteChar < 0) ? ReadChar () : dummyQuoteChar;
  1493. if (quoteChar != '\'' && quoteChar != '\"')
  1494. throw NotWFError ("an attribute value was not quoted");
  1495. currentAttributeToken.QuoteChar = (char) quoteChar;
  1496. IncrementAttributeValueToken ();
  1497. currentAttributeToken.ValueTokenStartIndex = currentAttributeValue;
  1498. currentAttributeValueToken.LineNumber = line;
  1499. currentAttributeValueToken.LinePosition = column;
  1500. bool incrementToken = false;
  1501. bool isNewToken = true;
  1502. bool loop = true;
  1503. int ch = 0;
  1504. currentAttributeValueToken.ValueBufferStart = valueBuffer.Length;
  1505. while (loop) {
  1506. ch = ReadChar ();
  1507. if (ch == quoteChar)
  1508. break;
  1509. if (incrementToken) {
  1510. IncrementAttributeValueToken ();
  1511. currentAttributeValueToken.ValueBufferStart = valueBuffer.Length;
  1512. currentAttributeValueToken.LineNumber = line;
  1513. currentAttributeValueToken.LinePosition = column;
  1514. incrementToken = false;
  1515. isNewToken = true;
  1516. }
  1517. switch (ch)
  1518. {
  1519. case '<':
  1520. throw NotWFError ("attribute values cannot contain '<'");
  1521. case -1:
  1522. if (dummyQuoteChar < 0)
  1523. throw NotWFError ("unexpected end of file in an attribute value");
  1524. else // Attribute value constructor.
  1525. loop = false;
  1526. break;
  1527. case '\r':
  1528. if (!normalization)
  1529. goto default;
  1530. if (PeekChar () == '\n')
  1531. continue; // skip '\r'.
  1532. //
  1533. // The csc in MS.NET 2.0 beta 1 barfs on this goto, so work around that
  1534. //
  1535. //goto case '\n';
  1536. if (!normalization)
  1537. goto default;
  1538. ch = ' ';
  1539. goto default;
  1540. case '\n':
  1541. case '\t':
  1542. // When Normalize = true, then replace
  1543. // all spaces to ' '
  1544. if (!normalization)
  1545. goto default;
  1546. ch = ' ';
  1547. goto default;
  1548. case '&':
  1549. if (PeekChar () == '#') {
  1550. ReadChar ();
  1551. ch = ReadCharacterReference ();
  1552. AppendValueChar (ch);
  1553. break;
  1554. }
  1555. // Check XML 1.0 section 3.1 WFC.
  1556. string entName = ReadName ();
  1557. Expect (';');
  1558. int predefined = XmlChar.GetPredefinedEntity (entName);
  1559. if (predefined < 0) {
  1560. CheckAttributeEntityReferenceWFC (entName);
  1561. #if NET_2_0
  1562. if (entityHandling == EntityHandling.ExpandEntities) {
  1563. string value = DTD.GenerateEntityAttributeText (entName);
  1564. foreach (char c in value)
  1565. AppendValueChar (c);
  1566. } else
  1567. #endif
  1568. {
  1569. currentAttributeValueToken.ValueBufferEnd = valueBuffer.Length;
  1570. currentAttributeValueToken.NodeType = XmlNodeType.Text;
  1571. if (!isNewToken)
  1572. IncrementAttributeValueToken ();
  1573. currentAttributeValueToken.Name = entName;
  1574. currentAttributeValueToken.Value = String.Empty;
  1575. currentAttributeValueToken.NodeType = XmlNodeType.EntityReference;
  1576. incrementToken = true;
  1577. }
  1578. }
  1579. else
  1580. AppendValueChar (predefined);
  1581. break;
  1582. default:
  1583. if (CharacterChecking && XmlChar.IsInvalid (ch))
  1584. throw NotWFError ("Invalid character was found.");
  1585. // FIXME: it might be optimized by the JIT later,
  1586. // AppendValueChar (ch);
  1587. {
  1588. if (ch < Char.MaxValue)
  1589. valueBuffer.Append ((char) ch);
  1590. else
  1591. AppendSurrogatePairValueChar (ch);
  1592. }
  1593. break;
  1594. }
  1595. isNewToken = false;
  1596. }
  1597. if (!incrementToken) {
  1598. currentAttributeValueToken.ValueBufferEnd = valueBuffer.Length;
  1599. currentAttributeValueToken.NodeType = XmlNodeType.Text;
  1600. }
  1601. currentAttributeToken.ValueTokenEndIndex = currentAttributeValue;
  1602. }
  1603. private void CheckAttributeEntityReferenceWFC (string entName)
  1604. {
  1605. DTDEntityDeclaration entDecl =
  1606. DTD == null ? null : DTD.EntityDecls [entName];
  1607. if (entDecl == null) {
  1608. if (entityHandling == EntityHandling.ExpandEntities
  1609. || (DTD != null && resolver != null && entDecl == null))
  1610. throw NotWFError (String.Format ("Referenced entity '{0}' does not exist.", entName));
  1611. else
  1612. return;
  1613. }
  1614. if (entDecl.HasExternalReference)
  1615. throw NotWFError ("Reference to external entities is not allowed in the value of an attribute.");
  1616. if (isStandalone && !entDecl.IsInternalSubset)
  1617. throw NotWFError ("Reference to external entities is not allowed in the internal subset.");
  1618. if (entDecl.EntityValue.IndexOf ('<') >= 0)
  1619. throw NotWFError ("Attribute must not contain character '<' either directly or indirectly by way of entity references.");
  1620. }
  1621. // The reader is positioned on the first character
  1622. // of the target.
  1623. //
  1624. // It may be xml declaration or processing instruction.
  1625. private void ReadProcessingInstruction ()
  1626. {
  1627. string target = ReadName ();
  1628. if (target == "xml") {
  1629. ReadXmlDeclaration ();
  1630. return;
  1631. } else if (target.ToLower (CultureInfo.InvariantCulture) == "xml")
  1632. throw NotWFError ("Not allowed processing instruction name which starts with 'X', 'M', 'L' was found.");
  1633. if (currentState == XmlNodeType.None)
  1634. currentState = XmlNodeType.XmlDeclaration;
  1635. if (!SkipWhitespace ())
  1636. if (PeekChar () != '?')
  1637. throw NotWFError ("Invalid processing instruction name was found.");
  1638. ClearValueBuffer ();
  1639. while (PeekChar () != -1) {
  1640. int ch = ReadChar ();
  1641. if (ch == '?' && PeekChar () == '>') {
  1642. ReadChar ();
  1643. break;
  1644. }
  1645. if (CharacterChecking && XmlChar.IsInvalid (ch))
  1646. throw NotWFError ("Invalid character was found.");
  1647. AppendValueChar (ch);
  1648. }
  1649. SetProperties (
  1650. XmlNodeType.ProcessingInstruction, // nodeType
  1651. target, // name
  1652. String.Empty, // prefix
  1653. target, // localName
  1654. false, // isEmptyElement
  1655. null, // value: create only when required
  1656. true // clearAttributes
  1657. );
  1658. }
  1659. // The reader is positioned after "<?xml "
  1660. private void ReadXmlDeclaration ()
  1661. {
  1662. if (currentState != XmlNodeType.None) {
  1663. throw NotWFError ("XML declaration cannot appear in this state.");
  1664. }
  1665. currentState = XmlNodeType.XmlDeclaration;
  1666. ClearAttributes ();
  1667. ReadAttributes (true); // They must have "version."
  1668. string version = GetAttribute ("version");
  1669. string message = null;
  1670. if (attributeTokens [0].Name != "version" || version != "1.0")
  1671. message = "Version 1.0 declaration is required in XML Declaration.";
  1672. else if (attributeCount > 1 &&
  1673. (attributeTokens [1].Name != "encoding" &&
  1674. attributeTokens [1].Name != "standalone"))
  1675. message = "Invalid Xml Declaration markup was found.";
  1676. else if (attributeCount > 2 && attributeTokens [2].Name != "standalone")
  1677. message = "Invalid Xml Declaration markup was found.";
  1678. string sa = GetAttribute ("standalone");
  1679. if (sa != null && sa != "yes" && sa != "no")
  1680. message = String.Format ("Only 'yes' or 'no' is allowed for standalone. Value was '{0}'", sa);
  1681. this.isStandalone = (sa == "yes");
  1682. if (message != null)
  1683. throw NotWFError (message);
  1684. SetProperties (
  1685. XmlNodeType.XmlDeclaration, // nodeType
  1686. "xml", // name
  1687. String.Empty, // prefix
  1688. "xml", // localName
  1689. false, // isEmptyElement
  1690. new string (currentTagBuffer, 6, currentTagLength - 6), // value
  1691. false // clearAttributes
  1692. );
  1693. Expect ("?>");
  1694. }
  1695. private void SkipTextDeclaration ()
  1696. {
  1697. this.currentState = XmlNodeType.Element;
  1698. if (PeekChar () != '<')
  1699. return;
  1700. ReadChar ();
  1701. if (PeekChar () != '?') {
  1702. peekCharsIndex = 0;
  1703. return;
  1704. }
  1705. ReadChar ();
  1706. while (peekCharsIndex < 6) {
  1707. if (PeekChar () < 0)
  1708. break;
  1709. else
  1710. ReadChar ();
  1711. }
  1712. if (new string (peekChars, 2, 4) != "xml ") {
  1713. if (new string (peekChars, 2, 3).ToLower (CultureInfo.InvariantCulture) == "xml") {
  1714. throw NotWFError ("Processing instruction name must not be character sequence 'X' 'M' 'L' with case insensitivity.");
  1715. }
  1716. peekCharsIndex = 0;
  1717. return;
  1718. }
  1719. SkipWhitespace ();
  1720. // version decl
  1721. if (PeekChar () == 'v') {
  1722. Expect ("version");
  1723. ExpectAfterWhitespace ('=');
  1724. SkipWhitespace ();
  1725. int quoteChar = ReadChar ();
  1726. char [] expect1_0 = new char [3];
  1727. int versionLength = 0;
  1728. switch (quoteChar) {
  1729. case '\'':
  1730. case '"':
  1731. while (PeekChar () != quoteChar) {
  1732. if (PeekChar () == -1)
  1733. throw NotWFError ("Invalid version declaration inside text declaration.");
  1734. else if (versionLength == 3)
  1735. throw NotWFError ("Invalid version number inside text declaration.");
  1736. else {
  1737. expect1_0 [versionLength] = (char) ReadChar ();
  1738. versionLength++;
  1739. if (versionLength == 3 && new String (expect1_0) != "1.0")
  1740. throw NotWFError ("Invalid version number inside text declaration.");
  1741. }
  1742. }
  1743. ReadChar ();
  1744. SkipWhitespace ();
  1745. break;
  1746. default:
  1747. throw NotWFError ("Invalid version declaration inside text declaration.");
  1748. }
  1749. }
  1750. if (PeekChar () == 'e') {
  1751. Expect ("encoding");
  1752. ExpectAfterWhitespace ('=');
  1753. SkipWhitespace ();
  1754. int quoteChar = ReadChar ();
  1755. switch (quoteChar) {
  1756. case '\'':
  1757. case '"':
  1758. while (PeekChar () != quoteChar)
  1759. if (ReadChar () == -1)
  1760. throw NotWFError ("Invalid encoding declaration inside text declaration.");
  1761. ReadChar ();
  1762. SkipWhitespace ();
  1763. break;
  1764. default:
  1765. throw NotWFError ("Invalid encoding declaration inside text declaration.");
  1766. }
  1767. // Encoding value should be checked inside XmlInputStream.
  1768. }
  1769. else
  1770. throw NotWFError ("Encoding declaration is mandatory in text declaration.");
  1771. Expect ("?>");
  1772. }
  1773. // The reader is positioned on the first character after
  1774. // the leading '<!'.
  1775. private void ReadDeclaration ()
  1776. {
  1777. int ch = PeekChar ();
  1778. switch (ch)
  1779. {
  1780. case '-':
  1781. Expect ("--");
  1782. ReadComment ();
  1783. break;
  1784. case '[':
  1785. ReadChar ();
  1786. Expect ("CDATA[");
  1787. ReadCDATA ();
  1788. break;
  1789. case 'D':
  1790. Expect ("DOCTYPE");
  1791. ReadDoctypeDecl ();
  1792. break;
  1793. default:
  1794. throw NotWFError ("Unexpected declaration markup was found.");
  1795. }
  1796. }
  1797. // The reader is positioned on the first character after
  1798. // the leading '<!--'.
  1799. private void ReadComment ()
  1800. {
  1801. if (currentState == XmlNodeType.None)
  1802. currentState = XmlNodeType.XmlDeclaration;
  1803. ClearValueBuffer ();
  1804. while (PeekChar () != -1) {
  1805. int ch = ReadChar ();
  1806. if (ch == '-' && PeekChar () == '-') {
  1807. ReadChar ();
  1808. if (PeekChar () != '>')
  1809. throw NotWFError ("comments cannot contain '--'");
  1810. ReadChar ();
  1811. break;
  1812. }
  1813. if (XmlChar.IsInvalid (ch))
  1814. throw NotWFError ("Not allowed character was found.");
  1815. AppendValueChar (ch);
  1816. }
  1817. SetProperties (
  1818. XmlNodeType.Comment, // nodeType
  1819. String.Empty, // name
  1820. String.Empty, // prefix
  1821. String.Empty, // localName
  1822. false, // isEmptyElement
  1823. null, // value: create only when required
  1824. true // clearAttributes
  1825. );
  1826. }
  1827. // The reader is positioned on the first character after
  1828. // the leading '<![CDATA['.
  1829. private void ReadCDATA ()
  1830. {
  1831. if (currentState != XmlNodeType.Element)
  1832. throw NotWFError ("CDATA section cannot appear in this state.");
  1833. ClearValueBuffer ();
  1834. bool skip = false;
  1835. int ch = 0;
  1836. while (PeekChar () != -1) {
  1837. if (!skip)
  1838. ch = ReadChar ();
  1839. skip = false;
  1840. if (ch == ']' && PeekChar () == ']') {
  1841. ch = ReadChar (); // ']'
  1842. if (PeekChar () == '>') {
  1843. ReadChar (); // '>'
  1844. break;
  1845. } else {
  1846. skip = true;
  1847. }
  1848. }
  1849. if (normalization && ch == '\r') {
  1850. ch = PeekChar ();
  1851. if (ch != '\n')
  1852. // append '\n' instead of '\r'.
  1853. AppendValueChar ('\n');
  1854. // otherwise, discard '\r'.
  1855. continue;
  1856. }
  1857. if (CharacterChecking && XmlChar.IsInvalid (ch))
  1858. throw NotWFError ("Invalid character was found.");
  1859. // FIXME: it might be optimized by the JIT later,
  1860. // AppendValueChar (ch);
  1861. {
  1862. if (ch < Char.MaxValue)
  1863. valueBuffer.Append ((char) ch);
  1864. else
  1865. AppendSurrogatePairValueChar (ch);
  1866. }
  1867. }
  1868. SetProperties (
  1869. XmlNodeType.CDATA, // nodeType
  1870. String.Empty, // name
  1871. String.Empty, // prefix
  1872. String.Empty, // localName
  1873. false, // isEmptyElement
  1874. null, // value: create only when required
  1875. true // clearAttributes
  1876. );
  1877. }
  1878. // The reader is positioned on the first character after
  1879. // the leading '<!DOCTYPE'.
  1880. private void ReadDoctypeDecl ()
  1881. {
  1882. if (prohibitDtd)
  1883. throw NotWFError ("Document Type Declaration (DTD) is prohibited in this XML.");
  1884. switch (currentState) {
  1885. case XmlNodeType.DocumentType:
  1886. case XmlNodeType.Element:
  1887. case XmlNodeType.EndElement:
  1888. throw NotWFError ("Document type cannot appear in this state.");
  1889. }
  1890. currentState = XmlNodeType.DocumentType;
  1891. string doctypeName = null;
  1892. string publicId = null;
  1893. string systemId = null;
  1894. int intSubsetStartLine = 0;
  1895. int intSubsetStartColumn = 0;
  1896. SkipWhitespace ();
  1897. doctypeName = ReadName ();
  1898. SkipWhitespace ();
  1899. switch(PeekChar ())
  1900. {
  1901. case 'S':
  1902. systemId = ReadSystemLiteral (true);
  1903. break;
  1904. case 'P':
  1905. publicId = ReadPubidLiteral ();
  1906. if (!SkipWhitespace ())
  1907. throw NotWFError ("Whitespace is required between PUBLIC id and SYSTEM id.");
  1908. systemId = ReadSystemLiteral (false);
  1909. break;
  1910. }
  1911. SkipWhitespace ();
  1912. if(PeekChar () == '[')
  1913. {
  1914. // read markupdecl etc. or end of decl
  1915. ReadChar ();
  1916. intSubsetStartLine = this.LineNumber;
  1917. intSubsetStartColumn = this.LinePosition;
  1918. int startPos = currentTagLength;
  1919. ReadInternalSubset ();
  1920. int endPos = currentTagLength - 1;
  1921. parserContext.InternalSubset = new string (currentTagBuffer, startPos, endPos - startPos);
  1922. }
  1923. // end of DOCTYPE decl.
  1924. ExpectAfterWhitespace ('>');
  1925. GenerateDTDObjectModel (doctypeName, publicId,
  1926. systemId, parserContext.InternalSubset,
  1927. intSubsetStartLine, intSubsetStartColumn);
  1928. // set properties for <!DOCTYPE> node
  1929. SetProperties (
  1930. XmlNodeType.DocumentType, // nodeType
  1931. doctypeName, // name
  1932. String.Empty, // prefix
  1933. doctypeName, // localName
  1934. false, // isEmptyElement
  1935. parserContext.InternalSubset, // value
  1936. true // clearAttributes
  1937. );
  1938. if (publicId != null)
  1939. AddDtdAttribute ("PUBLIC", publicId);
  1940. if (systemId != null)
  1941. AddDtdAttribute ("SYSTEM", systemId);
  1942. currentAttribute = currentAttributeValue = -1;
  1943. }
  1944. internal DTDObjectModel GenerateDTDObjectModel (string name, string publicId,
  1945. string systemId, string internalSubset)
  1946. {
  1947. return GenerateDTDObjectModel (name, publicId, systemId, internalSubset, 0, 0);
  1948. }
  1949. internal DTDObjectModel GenerateDTDObjectModel (string name, string publicId,
  1950. string systemId, string internalSubset, int intSubsetStartLine, int intSubsetStartColumn)
  1951. {
  1952. // now compile DTD
  1953. parserContext.Dtd = new DTDObjectModel (this.NameTable); // merges both internal and external subsets in the meantime,
  1954. DTD.BaseURI = BaseURI;
  1955. DTD.Name = name;
  1956. DTD.PublicId = publicId;
  1957. DTD.SystemId = systemId;
  1958. DTD.InternalSubset = internalSubset;
  1959. DTD.XmlResolver = resolver;
  1960. DTD.IsStandalone = isStandalone;
  1961. DTD.LineNumber = line;
  1962. DTD.LinePosition = column;
  1963. DTDReader dr = new DTDReader (DTD, intSubsetStartLine, intSubsetStartColumn);
  1964. dr.Normalization = this.normalization;
  1965. return dr.GenerateDTDObjectModel ();
  1966. }
  1967. private enum DtdInputState
  1968. {
  1969. Free = 1,
  1970. ElementDecl,
  1971. AttlistDecl,
  1972. EntityDecl,
  1973. NotationDecl,
  1974. PI,
  1975. Comment,
  1976. InsideSingleQuoted,
  1977. InsideDoubleQuoted,
  1978. }
  1979. private class DtdInputStateStack
  1980. {
  1981. Stack intern = new Stack ();
  1982. public DtdInputStateStack ()
  1983. {
  1984. Push (DtdInputState.Free);
  1985. }
  1986. public DtdInputState Peek ()
  1987. {
  1988. return (DtdInputState) intern.Peek ();
  1989. }
  1990. public DtdInputState Pop ()
  1991. {
  1992. return (DtdInputState) intern.Pop ();
  1993. }
  1994. public void Push (DtdInputState val)
  1995. {
  1996. intern.Push (val);
  1997. }
  1998. }
  1999. DtdInputStateStack stateStack = new DtdInputStateStack ();
  2000. DtdInputState State {
  2001. get { return stateStack.Peek (); }
  2002. }
  2003. // Simply read but not generate any result.
  2004. private void ReadInternalSubset ()
  2005. {
  2006. bool continueParse = true;
  2007. while (continueParse) {
  2008. switch (ReadChar ()) {
  2009. case ']':
  2010. switch (State) {
  2011. case DtdInputState.Free:
  2012. continueParse = false;
  2013. break;
  2014. case DtdInputState.InsideDoubleQuoted:
  2015. continue;
  2016. case DtdInputState.InsideSingleQuoted:
  2017. continue;
  2018. default:
  2019. throw NotWFError ("unexpected end of file at DTD.");
  2020. }
  2021. break;
  2022. case -1:
  2023. throw NotWFError ("unexpected end of file at DTD.");
  2024. case '<':
  2025. switch (State) {
  2026. case DtdInputState.InsideDoubleQuoted:
  2027. case DtdInputState.InsideSingleQuoted:
  2028. case DtdInputState.Comment:
  2029. continue; // well-formed
  2030. }
  2031. int c = ReadChar ();
  2032. switch (c) {
  2033. case '?':
  2034. stateStack.Push (DtdInputState.PI);
  2035. break;
  2036. case '!':
  2037. switch (ReadChar ()) {
  2038. case 'E':
  2039. switch (ReadChar ()) {
  2040. case 'L':
  2041. Expect ("EMENT");
  2042. stateStack.Push (DtdInputState.ElementDecl);
  2043. break;
  2044. case 'N':
  2045. Expect ("TITY");
  2046. stateStack.Push (DtdInputState.EntityDecl);
  2047. break;
  2048. default:
  2049. throw NotWFError ("unexpected token '<!E'.");
  2050. }
  2051. break;
  2052. case 'A':
  2053. Expect ("TTLIST");
  2054. stateStack.Push (DtdInputState.AttlistDecl);
  2055. break;
  2056. case 'N':
  2057. Expect ("OTATION");
  2058. stateStack.Push (DtdInputState.NotationDecl);
  2059. break;
  2060. case '-':
  2061. Expect ('-');
  2062. stateStack.Push (DtdInputState.Comment);
  2063. break;
  2064. }
  2065. break;
  2066. default:
  2067. throw NotWFError (String.Format ("unexpected '<{0}'.", (char) c));
  2068. }
  2069. break;
  2070. case '\'':
  2071. if (State == DtdInputState.InsideSingleQuoted)
  2072. stateStack.Pop ();
  2073. else if (State != DtdInputState.InsideDoubleQuoted && State != DtdInputState.Comment)
  2074. stateStack.Push (DtdInputState.InsideSingleQuoted);
  2075. break;
  2076. case '"':
  2077. if (State == DtdInputState.InsideDoubleQuoted)
  2078. stateStack.Pop ();
  2079. else if (State != DtdInputState.InsideSingleQuoted && State != DtdInputState.Comment)
  2080. stateStack.Push (DtdInputState.InsideDoubleQuoted);
  2081. break;
  2082. case '>':
  2083. switch (State) {
  2084. case DtdInputState.ElementDecl:
  2085. goto case DtdInputState.NotationDecl;
  2086. case DtdInputState.AttlistDecl:
  2087. goto case DtdInputState.NotationDecl;
  2088. case DtdInputState.EntityDecl:
  2089. goto case DtdInputState.NotationDecl;
  2090. case DtdInputState.NotationDecl:
  2091. stateStack.Pop ();
  2092. break;
  2093. case DtdInputState.InsideDoubleQuoted:
  2094. case DtdInputState.InsideSingleQuoted:
  2095. case DtdInputState.Comment:
  2096. continue;
  2097. default:
  2098. throw NotWFError ("unexpected token '>'");
  2099. }
  2100. break;
  2101. case '?':
  2102. if (State == DtdInputState.PI) {
  2103. if (ReadChar () == '>')
  2104. stateStack.Pop ();
  2105. }
  2106. break;
  2107. case '-':
  2108. if (State == DtdInputState.Comment) {
  2109. if (PeekChar () == '-') {
  2110. ReadChar ();
  2111. Expect ('>');
  2112. stateStack.Pop ();
  2113. }
  2114. }
  2115. break;
  2116. case '%':
  2117. if (State != DtdInputState.Free && State != DtdInputState.EntityDecl && State != DtdInputState.Comment && State != DtdInputState.InsideDoubleQuoted && State != DtdInputState.InsideSingleQuoted)
  2118. throw NotWFError ("Parameter Entity Reference cannot appear as a part of markupdecl (see XML spec 2.8).");
  2119. break;
  2120. }
  2121. }
  2122. }
  2123. // The reader is positioned on the first 'S' of "SYSTEM".
  2124. private string ReadSystemLiteral (bool expectSYSTEM)
  2125. {
  2126. if(expectSYSTEM) {
  2127. Expect ("SYSTEM");
  2128. if (!SkipWhitespace ())
  2129. throw NotWFError ("Whitespace is required after 'SYSTEM'.");
  2130. }
  2131. else
  2132. SkipWhitespace ();
  2133. int quoteChar = ReadChar (); // apos or quot
  2134. int c = 0;
  2135. ClearValueBuffer ();
  2136. while (c != quoteChar) {
  2137. c = ReadChar ();
  2138. if (c < 0)
  2139. throw NotWFError ("Unexpected end of stream in ExternalID.");
  2140. if (c != quoteChar)
  2141. AppendValueChar (c);
  2142. }
  2143. return CreateValueString ();
  2144. }
  2145. private string ReadPubidLiteral()
  2146. {
  2147. Expect ("PUBLIC");
  2148. if (!SkipWhitespace ())
  2149. throw NotWFError ("Whitespace is required after 'PUBLIC'.");
  2150. int quoteChar = ReadChar ();
  2151. int c = 0;
  2152. ClearValueBuffer ();
  2153. while(c != quoteChar)
  2154. {
  2155. c = ReadChar ();
  2156. if(c < 0) throw NotWFError ("Unexpected end of stream in ExternalID.");
  2157. if(c != quoteChar && !XmlChar.IsPubidChar (c))
  2158. throw NotWFError (String.Format ("character '{0}' not allowed for PUBLIC ID", (char)c ));
  2159. if (c != quoteChar)
  2160. AppendValueChar (c);
  2161. }
  2162. return CreateValueString ();
  2163. }
  2164. // The reader is positioned on the first character
  2165. // of the name.
  2166. private string ReadName ()
  2167. {
  2168. string prefix, local;
  2169. return ReadName (out prefix, out local);
  2170. }
  2171. private string ReadName (out string prefix, out string localName)
  2172. {
  2173. // FIXME: need to reject non-QName names?
  2174. int ch = PeekChar ();
  2175. if (!XmlChar.IsFirstNameChar (ch))
  2176. throw NotWFError (String.Format (CultureInfo.InvariantCulture, "a name did not start with a legal character {0} ({1})", ch, (char) ch));
  2177. nameLength = 0;
  2178. ch = ReadChar ();
  2179. // AppendNameChar (ch);
  2180. {
  2181. if (nameLength == nameCapacity)
  2182. ExpandNameCapacity ();
  2183. if (ch < Char.MaxValue)
  2184. nameBuffer [nameLength++] = (char) ch;
  2185. else
  2186. AppendSurrogatePairNameChar (ch);
  2187. }
  2188. int colonAt = -1;
  2189. while (XmlChar.IsNameChar (PeekChar ())) {
  2190. ch = ReadChar ();
  2191. if (namespaces && colonAt < 0 && ch == ':')
  2192. colonAt = nameLength;
  2193. // AppendNameChar (ch);
  2194. {
  2195. if (nameLength == nameCapacity)
  2196. ExpandNameCapacity ();
  2197. if (ch < Char.MaxValue)
  2198. nameBuffer [nameLength++] = (char) ch;
  2199. else
  2200. AppendSurrogatePairNameChar (ch);
  2201. }
  2202. }
  2203. string name = parserContext.NameTable.Add (nameBuffer, 0, nameLength);
  2204. if (namespaces && colonAt > 0) {
  2205. prefix = parserContext.NameTable.Add (nameBuffer, 0, colonAt);
  2206. localName = parserContext.NameTable.Add (nameBuffer, colonAt + 1, nameLength - colonAt - 1);
  2207. }
  2208. else {
  2209. prefix = String.Empty;
  2210. localName = name;
  2211. }
  2212. return name;
  2213. }
  2214. // Read the next character and compare it against the
  2215. // specified character.
  2216. private void Expect (int expected)
  2217. {
  2218. int ch = ReadChar ();
  2219. if (ch != expected) {
  2220. throw NotWFError (String.Format (CultureInfo.InvariantCulture,
  2221. "expected '{0}' ({1:X}) but found '{2}' ({3:X})",
  2222. (char) expected,
  2223. expected,
  2224. ch < 0 ? (object) "EOF" : (char) ch,
  2225. ch));
  2226. }
  2227. }
  2228. private void Expect (string expected)
  2229. {
  2230. int len = expected.Length;
  2231. for(int i=0; i< len; i++)
  2232. Expect (expected[i]);
  2233. }
  2234. private void ExpectAfterWhitespace (char c)
  2235. {
  2236. while (true) {
  2237. int i = ReadChar ();
  2238. if (i < 0x21 && XmlChar.IsWhitespace (i))
  2239. continue;
  2240. if (c != i)
  2241. throw NotWFError (String.Format (CultureInfo.InvariantCulture, "Expected {0}, but found {1} [{2}]", c, i < 0 ? (object) "EOF" : (char) i, i));
  2242. break;
  2243. }
  2244. }
  2245. // Does not consume the first non-whitespace character.
  2246. private bool SkipWhitespace ()
  2247. {
  2248. // FIXME: It should be inlined by the JIT.
  2249. // bool skipped = XmlChar.IsWhitespace (PeekChar ());
  2250. int ch = PeekChar ();
  2251. bool skipped = (ch == 0x20 || ch == 0x9 || ch == 0xA || ch == 0xD);
  2252. if (!skipped)
  2253. return false;
  2254. ReadChar ();
  2255. // FIXME: It should be inlined by the JIT.
  2256. // while (XmlChar.IsWhitespace (PeekChar ()))
  2257. // ReadChar ();
  2258. while ((ch = PeekChar ()) == 0x20 || ch == 0x9 || ch == 0xA || ch == 0xD)
  2259. ReadChar ();
  2260. return skipped;
  2261. }
  2262. private void ReadWhitespace ()
  2263. {
  2264. if (currentState == XmlNodeType.None)
  2265. currentState = XmlNodeType.XmlDeclaration;
  2266. ClearValueBuffer ();
  2267. int ch = PeekChar ();
  2268. do {
  2269. // FIXME: it might be optimized by the JIT later,
  2270. // AppendValueChar (ReadChar ());
  2271. {
  2272. ch = ReadChar ();
  2273. if (ch < Char.MaxValue)
  2274. valueBuffer.Append ((char) ch);
  2275. else
  2276. AppendSurrogatePairValueChar (ch);
  2277. }
  2278. // FIXME: It should be inlined by the JIT.
  2279. // } while ((ch = PeekChar ()) != -1 && XmlChar.IsWhitespace (ch));
  2280. ch = PeekChar ();
  2281. } while (ch == 0x20 || ch == 0x9 || ch == 0xA || ch == 0xD);
  2282. if (currentState == XmlNodeType.Element && ch != -1 && ch != '<')
  2283. ReadText (false);
  2284. else {
  2285. XmlNodeType nodeType = (this.XmlSpace == XmlSpace.Preserve) ?
  2286. XmlNodeType.SignificantWhitespace : XmlNodeType.Whitespace;
  2287. SetProperties (nodeType,
  2288. String.Empty,
  2289. String.Empty,
  2290. String.Empty,
  2291. false,
  2292. null, // value: create only when required
  2293. true);
  2294. }
  2295. return;
  2296. }
  2297. // Returns -1 if it should throw an error.
  2298. private int ReadCharsInternal (char [] buffer, int offset, int length)
  2299. {
  2300. shouldSkipUntilEndTag = true;
  2301. int bufIndex = offset;
  2302. for (int i = 0; i < length; i++) {
  2303. int c = PeekChar ();
  2304. switch (c) {
  2305. case -1:
  2306. throw NotWFError ("Unexpected end of xml.");
  2307. case '<':
  2308. ReadChar ();
  2309. if (PeekChar () != '/') {
  2310. buffer [bufIndex++] = '<';
  2311. continue;
  2312. }
  2313. // Seems to skip immediate EndElement
  2314. Expect ('/');
  2315. if (depthUp) {
  2316. depth++;
  2317. depthUp = false;
  2318. }
  2319. ReadEndTag ();
  2320. shouldSkipUntilEndTag = false;
  2321. Read (); // move to the next node
  2322. return i;
  2323. default:
  2324. ReadChar ();
  2325. if (c < Char.MaxValue)
  2326. buffer [bufIndex++] = (char) c;
  2327. else {
  2328. buffer [bufIndex++] = (char) (c / 0x10000 + 0xD800 - 1);
  2329. buffer [bufIndex++] = (char) (c % 0x10000 + 0xDC00);
  2330. }
  2331. break;
  2332. }
  2333. }
  2334. return length;
  2335. }
  2336. private bool ReadUntilEndTag ()
  2337. {
  2338. if (Depth == 0)
  2339. currentState = XmlNodeType.EndElement;
  2340. int ch;
  2341. do {
  2342. ch = ReadChar ();
  2343. switch (ch) {
  2344. case -1:
  2345. throw NotWFError ("Unexpected end of xml.");
  2346. case '<':
  2347. if (PeekChar () != '/')
  2348. continue;
  2349. ReadChar ();
  2350. string name = ReadName ();
  2351. if (name != elementNames [elementNameStackPos - 1])
  2352. continue;
  2353. Expect ('>');
  2354. depth--;
  2355. elementNames [--elementNameStackPos] = null;
  2356. return Read ();
  2357. }
  2358. } while (true);
  2359. }
  2360. #endregion
  2361. }
  2362. }