XmlTextReader.cs 69 KB

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