XmlTextReader.cs 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656
  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 Evidence {
  165. get { return base.Evidence; }
  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. public bool ProhibitDtd {
  235. get { return prohibitDtd; }
  236. set { prohibitDtd = value; }
  237. }
  238. #endif
  239. public override char QuoteChar {
  240. get { return cursorToken.QuoteChar; }
  241. }
  242. public override ReadState ReadState {
  243. get { return readState; }
  244. }
  245. public override string Value {
  246. get { return cursorToken.Value != null ? cursorToken.Value : String.Empty; }
  247. }
  248. public WhitespaceHandling WhitespaceHandling {
  249. get { return whitespaceHandling; }
  250. set { whitespaceHandling = value; }
  251. }
  252. public override string XmlLang {
  253. get { return parserContext.XmlLang; }
  254. }
  255. public XmlResolver XmlResolver {
  256. set { resolver = value; }
  257. }
  258. public override XmlSpace XmlSpace {
  259. get { return parserContext.XmlSpace; }
  260. }
  261. #endregion
  262. #region Methods
  263. public override void Close ()
  264. {
  265. readState = ReadState.Closed;
  266. cursorToken.Clear ();
  267. currentToken.Clear ();
  268. attributeCount = 0;
  269. if (reader != null)
  270. reader.Close ();
  271. }
  272. public override string GetAttribute (int i)
  273. {
  274. if (i >= attributeCount)
  275. throw new ArgumentOutOfRangeException ("i is smaller than AttributeCount");
  276. else {
  277. return attributeTokens [i].Value;
  278. }
  279. }
  280. // MS.NET 1.0 msdn says that this method returns String.Empty
  281. // for absent attribute, but in fact it returns null.
  282. // This description is corrected in MS.NET 1.1 msdn.
  283. public override string GetAttribute (string name)
  284. {
  285. for (int i = 0; i < attributeCount; i++)
  286. if (attributeTokens [i].Name == name)
  287. return attributeTokens [i].Value;
  288. return null;
  289. }
  290. private int GetIndexOfQualifiedAttribute (string localName, string namespaceURI)
  291. {
  292. for (int i = 0; i < attributeCount; i++) {
  293. XmlAttributeTokenInfo ti = attributeTokens [i];
  294. if (ti.LocalName == localName && ti.NamespaceURI == namespaceURI)
  295. return i;
  296. }
  297. return -1;
  298. }
  299. internal XmlParserContext GetInternalParserContext ()
  300. {
  301. return parserContext;
  302. }
  303. public override string GetAttribute (string localName, string namespaceURI)
  304. {
  305. int idx = this.GetIndexOfQualifiedAttribute (localName, namespaceURI);
  306. if (idx < 0)
  307. return null;
  308. return attributeTokens [idx].Value;
  309. }
  310. public TextReader GetRemainder ()
  311. {
  312. if (peekCharsIndex == peekCharsLength)
  313. return reader;
  314. return new StringReader (new string (peekChars, peekCharsIndex, peekCharsLength - peekCharsIndex) + reader.ReadToEnd ());
  315. }
  316. bool IXmlLineInfo.HasLineInfo ()
  317. {
  318. return true;
  319. }
  320. public override string LookupNamespace (string prefix)
  321. {
  322. return LookupNamespace (prefix, false);
  323. }
  324. internal string LookupNamespace (string prefix, bool atomizedName)
  325. {
  326. return parserContext.NamespaceManager.LookupNamespace (prefix, atomizedName);
  327. }
  328. public override void MoveToAttribute (int i)
  329. {
  330. if (i >= attributeCount)
  331. throw new ArgumentOutOfRangeException ("attribute index out of range.");
  332. currentAttribute = i;
  333. currentAttributeValue = -1;
  334. cursorToken = attributeTokens [i];
  335. }
  336. public override bool MoveToAttribute (string name)
  337. {
  338. for (int i = 0; i < attributeCount; i++) {
  339. XmlAttributeTokenInfo ti = attributeTokens [i];
  340. if (ti.Name == name) {
  341. MoveToAttribute (i);
  342. return true;
  343. }
  344. }
  345. return false;
  346. }
  347. public override bool MoveToAttribute (string localName, string namespaceName)
  348. {
  349. int idx = GetIndexOfQualifiedAttribute (localName, namespaceName);
  350. if (idx < 0)
  351. return false;
  352. MoveToAttribute (idx);
  353. return true;
  354. }
  355. public override bool MoveToElement ()
  356. {
  357. if (currentToken == null) // for attribute .ctor()
  358. return false;
  359. if (cursorToken == currentToken)
  360. return false;
  361. if (currentAttribute >= 0) {
  362. currentAttribute = -1;
  363. currentAttributeValue = -1;
  364. cursorToken = currentToken;
  365. return true;
  366. }
  367. else
  368. return false;
  369. }
  370. public override bool MoveToFirstAttribute ()
  371. {
  372. if (attributeCount == 0)
  373. return false;
  374. MoveToElement ();
  375. return MoveToNextAttribute ();
  376. }
  377. public override bool MoveToNextAttribute ()
  378. {
  379. if (currentAttribute == 0 && attributeCount == 0)
  380. return false;
  381. if (currentAttribute + 1 < attributeCount) {
  382. currentAttribute++;
  383. currentAttributeValue = -1;
  384. cursorToken = attributeTokens [currentAttribute];
  385. return true;
  386. }
  387. else
  388. return false;
  389. }
  390. public override bool Read ()
  391. {
  392. if (startNodeType == XmlNodeType.Attribute) {
  393. if (currentAttribute == 0)
  394. return false; // already read.
  395. ClearAttributes ();
  396. IncrementAttributeToken ();
  397. ReadAttributeValueTokens ('"');
  398. cursorToken = attributeTokens [0];
  399. currentAttributeValue = -1;
  400. readState = ReadState.Interactive;
  401. return true;
  402. }
  403. bool more = false;
  404. readState = ReadState.Interactive;
  405. currentLinkedNodeLineNumber = line;
  406. currentLinkedNodeLinePosition = column;
  407. useProceedingLineInfo = true;
  408. cursorToken = currentToken;
  409. attributeCount = 0;
  410. currentAttribute = currentAttributeValue = -1;
  411. currentToken.Clear ();
  412. // It was moved from end of ReadStartTag ().
  413. if (depthUp) {
  414. ++depth;
  415. depthUp = false;
  416. }
  417. if (shouldSkipUntilEndTag) {
  418. shouldSkipUntilEndTag = false;
  419. return ReadUntilEndTag ();
  420. }
  421. base64CacheStartsAt = -1;
  422. more = ReadContent ();
  423. if (!more && startNodeType == XmlNodeType.Document && currentState != XmlNodeType.EndElement)
  424. throw new XmlException ("Document element did not appear.");
  425. useProceedingLineInfo = false;
  426. return more;
  427. }
  428. public override bool ReadAttributeValue ()
  429. {
  430. if (readState == ReadState.Initial && startNodeType == XmlNodeType.Attribute) {
  431. Read ();
  432. }
  433. if (currentAttribute < 0)
  434. return false;
  435. XmlAttributeTokenInfo ti = attributeTokens [currentAttribute];
  436. if (currentAttributeValue < 0)
  437. currentAttributeValue = ti.ValueTokenStartIndex - 1;
  438. if (currentAttributeValue < ti.ValueTokenEndIndex) {
  439. currentAttributeValue++;
  440. cursorToken = attributeValueTokens [currentAttributeValue];
  441. return true;
  442. }
  443. else
  444. return false;
  445. }
  446. public int ReadBase64 (byte [] buffer, int offset, int length)
  447. {
  448. if (offset < 0)
  449. throw new ArgumentOutOfRangeException ("offset", offset, "Offset must be non-negative integer.");
  450. else if (length < 0)
  451. throw new ArgumentOutOfRangeException ("length", length, "Length must be non-negative integer.");
  452. else if (buffer.Length < offset + length)
  453. throw new ArgumentOutOfRangeException ("buffer length is smaller than the sum of offset and length.");
  454. if (length == 0) // It does not raise an error.
  455. return 0;
  456. int bufIndex = offset;
  457. int bufLast = offset + length;
  458. if (base64CacheStartsAt >= 0) {
  459. for (int i = base64CacheStartsAt; i < 3; i++) {
  460. buffer [bufIndex++] = base64Cache [base64CacheStartsAt++];
  461. if (bufIndex == bufLast)
  462. return bufLast - offset;
  463. }
  464. }
  465. for (int i = 0; i < 3; i++)
  466. base64Cache [i] = 0;
  467. base64CacheStartsAt = -1;
  468. int max = (int) System.Math.Ceiling (4.0 / 3 * length);
  469. int additional = max % 4;
  470. if (additional > 0)
  471. max += 4 - additional;
  472. char [] chars = new char [max];
  473. int charsLength = ReadChars (chars, 0, max);
  474. byte b = 0;
  475. byte work = 0;
  476. for (int i = 0; i < charsLength - 3; i += 4) {
  477. b = (byte) (GetBase64Byte (chars [i]) << 2);
  478. if (bufIndex < bufLast)
  479. buffer [bufIndex] = b;
  480. else {
  481. if (base64CacheStartsAt < 0)
  482. base64CacheStartsAt = 0;
  483. base64Cache [0] = b;
  484. }
  485. // charsLength mod 4 might not equals to 0.
  486. if (i + 1 == charsLength)
  487. break;
  488. b = GetBase64Byte (chars [i + 1]);
  489. work = (byte) (b >> 4);
  490. if (bufIndex < bufLast) {
  491. buffer [bufIndex] += work;
  492. bufIndex++;
  493. }
  494. else
  495. base64Cache [0] += work;
  496. work = (byte) ((b & 0xf) << 4);
  497. if (bufIndex < bufLast) {
  498. buffer [bufIndex] = work;
  499. }
  500. else {
  501. if (base64CacheStartsAt < 0)
  502. base64CacheStartsAt = 1;
  503. base64Cache [1] = work;
  504. }
  505. if (i + 2 == charsLength)
  506. break;
  507. b = GetBase64Byte (chars [i + 2]);
  508. work = (byte) (b >> 2);
  509. if (bufIndex < bufLast) {
  510. buffer [bufIndex] += work;
  511. bufIndex++;
  512. }
  513. else
  514. base64Cache [1] += work;
  515. work = (byte) ((b & 3) << 6);
  516. if (bufIndex < bufLast)
  517. buffer [bufIndex] = work;
  518. else {
  519. if (base64CacheStartsAt < 0)
  520. base64CacheStartsAt = 2;
  521. base64Cache [2] = work;
  522. }
  523. if (i + 3 == charsLength)
  524. break;
  525. work = GetBase64Byte (chars [i + 3]);
  526. if (bufIndex < bufLast) {
  527. buffer [bufIndex] += work;
  528. bufIndex++;
  529. }
  530. else
  531. base64Cache [2] += work;
  532. }
  533. return System.Math.Min (bufLast - offset, bufIndex - offset);
  534. }
  535. public int ReadBinHex (byte [] buffer, int offset, int length)
  536. {
  537. if (offset < 0)
  538. throw new ArgumentOutOfRangeException ("offset", offset, "Offset must be non-negative integer.");
  539. else if (length < 0)
  540. throw new ArgumentOutOfRangeException ("length", length, "Length must be non-negative integer.");
  541. else if (buffer.Length < offset + length)
  542. throw new ArgumentOutOfRangeException ("buffer length is smaller than the sum of offset and length.");
  543. if (length == 0)
  544. return 0;
  545. char [] chars = new char [length * 2];
  546. int charsLength = ReadChars (chars, 0, length * 2);
  547. return XmlConvert.FromBinHexString (chars, offset, charsLength, buffer);
  548. }
  549. public int ReadChars (char [] buffer, int offset, int length)
  550. {
  551. return ReadCharsInternal (buffer, offset, length);
  552. }
  553. #if NET_1_1
  554. #else
  555. public override string ReadInnerXml ()
  556. {
  557. return ReadInnerXmlInternal ();
  558. }
  559. public override string ReadOuterXml ()
  560. {
  561. return ReadOuterXmlInternal ();
  562. }
  563. public override string ReadString ()
  564. {
  565. return ReadStringInternal ();
  566. }
  567. #endif
  568. public void ResetState ()
  569. {
  570. Init ();
  571. }
  572. public override void ResolveEntity ()
  573. {
  574. // XmlTextReader does not resolve entities.
  575. throw new InvalidOperationException ("XmlTextReader cannot resolve external entities.");
  576. }
  577. #if NET_2_0
  578. [MonoTODO ("Implement for performance reason")]
  579. public override void Skip ()
  580. {
  581. base.Skip ();
  582. }
  583. #endif
  584. #endregion
  585. #region Internals
  586. // Parsed DTD Objects
  587. #if DTD_HANDLE_EVENTS
  588. internal event ValidationEventHandler ValidationEventHandler;
  589. #endif
  590. internal DTDObjectModel DTD {
  591. get { return parserContext.Dtd; }
  592. }
  593. internal XmlResolver Resolver {
  594. get { return resolver; }
  595. }
  596. #endregion
  597. #region Privates
  598. internal class XmlTokenInfo
  599. {
  600. public XmlTokenInfo (XmlTextReader xtr, bool isPrimaryToken)
  601. {
  602. this.isPrimaryToken = isPrimaryToken;
  603. Reader = xtr;
  604. Clear ();
  605. }
  606. bool isPrimaryToken;
  607. string valueCache;
  608. protected XmlTextReader Reader;
  609. public string Name;
  610. public string LocalName;
  611. public string Prefix;
  612. public string NamespaceURI;
  613. public bool IsEmptyElement;
  614. public char QuoteChar;
  615. public int LineNumber;
  616. public int LinePosition;
  617. public XmlNodeType NodeType;
  618. public virtual string Value {
  619. get {
  620. if (valueCache != null)
  621. return valueCache;
  622. switch (NodeType) {
  623. case XmlNodeType.Text:
  624. case XmlNodeType.SignificantWhitespace:
  625. case XmlNodeType.Whitespace:
  626. case XmlNodeType.Comment:
  627. case XmlNodeType.CDATA:
  628. case XmlNodeType.ProcessingInstruction:
  629. valueCache = Reader.CreateValueString ();
  630. return valueCache;
  631. }
  632. return null;
  633. }
  634. set { valueCache = value; }
  635. }
  636. public virtual void Clear ()
  637. {
  638. valueCache = null;
  639. NodeType = XmlNodeType.None;
  640. Name = LocalName = Prefix = NamespaceURI = String.Empty;
  641. IsEmptyElement = false;
  642. QuoteChar = '"';
  643. LineNumber = LinePosition = 0;
  644. }
  645. internal virtual void FillNames ()
  646. {
  647. if (Reader.Namespaces) {
  648. int indexOfColon = -1;
  649. switch (NodeType) {
  650. case XmlNodeType.Attribute:
  651. case XmlNodeType.Element:
  652. case XmlNodeType.EndElement:
  653. indexOfColon = Name.IndexOf (':');
  654. break;
  655. }
  656. if (indexOfColon == -1) {
  657. Prefix = String.Empty;
  658. LocalName = Name;
  659. } else {
  660. // This improves speed by at least nearly 5%, but eats more memory at least nearly 0.3%
  661. // However, this might be reverted if NameTable is got improved.
  662. char [] nameArr = Name.ToCharArray ();
  663. Prefix = Reader.NameTable.Add (nameArr, 0, indexOfColon);
  664. LocalName = Reader.NameTable.Add (nameArr, indexOfColon + 1, nameArr.Length - indexOfColon - 1);
  665. // Prefix = Reader.NameTable.Add (Name.Substring (0, indexOfColon));
  666. // LocalName = Reader.NameTable.Add (Name.Substring (indexOfColon + 1));
  667. }
  668. // NamespaceURI
  669. switch (NodeType) {
  670. case XmlNodeType.Attribute:
  671. if (Prefix.Length == 0)
  672. NamespaceURI = string.Empty;
  673. else
  674. NamespaceURI = Reader.LookupNamespace (Prefix, true);
  675. break;
  676. case XmlNodeType.Element:
  677. case XmlNodeType.EndElement:
  678. NamespaceURI = Reader.LookupNamespace (Prefix, true);
  679. break;
  680. default:
  681. NamespaceURI = "";
  682. break;
  683. }
  684. } else {
  685. Prefix = String.Empty;
  686. LocalName = Name;
  687. }
  688. }
  689. }
  690. internal class XmlAttributeTokenInfo : XmlTokenInfo
  691. {
  692. public XmlAttributeTokenInfo (XmlTextReader reader)
  693. : base (reader, false)
  694. {
  695. NodeType = XmlNodeType.Attribute;
  696. }
  697. public int ValueTokenStartIndex;
  698. public int ValueTokenEndIndex;
  699. string valueCache;
  700. bool cachedNormalization;
  701. StringBuilder tmpBuilder = new StringBuilder ();
  702. public override string Value {
  703. get {
  704. if (cachedNormalization != Reader.Normalization)
  705. valueCache = null;
  706. if (valueCache != null)
  707. return valueCache;
  708. cachedNormalization = Reader.Normalization;
  709. // An empty value should return String.Empty.
  710. if (ValueTokenStartIndex == ValueTokenEndIndex) {
  711. XmlTokenInfo ti = Reader.attributeValueTokens [ValueTokenStartIndex];
  712. if (ti.NodeType == XmlNodeType.EntityReference)
  713. valueCache = String.Concat ("&", ti.Name, ";");
  714. else
  715. valueCache = ti.Value;
  716. if (cachedNormalization)
  717. NormalizeSpaces ();
  718. return valueCache;
  719. }
  720. tmpBuilder.Length = 0;
  721. for (int i = ValueTokenStartIndex; i <= ValueTokenEndIndex; i++) {
  722. XmlTokenInfo ti = Reader.attributeValueTokens [i];
  723. if (ti.NodeType == XmlNodeType.Text)
  724. tmpBuilder.Append (ti.Value);
  725. else {
  726. tmpBuilder.Append ('&');
  727. tmpBuilder.Append (ti.Name);
  728. tmpBuilder.Append (';');
  729. }
  730. }
  731. valueCache = tmpBuilder.ToString ();
  732. if (cachedNormalization)
  733. NormalizeSpaces ();
  734. return valueCache;
  735. }
  736. set { valueCache = value; }
  737. }
  738. public override void Clear ()
  739. {
  740. base.Clear ();
  741. valueCache = null;
  742. NodeType = XmlNodeType.Attribute;
  743. ValueTokenStartIndex = ValueTokenEndIndex = 0;
  744. }
  745. internal override void FillNames ()
  746. {
  747. base.FillNames ();
  748. if (Prefix == "xmlns" || Name == "xmlns")
  749. NamespaceURI = XmlNamespaceManager.XmlnsXmlns;
  750. }
  751. private void NormalizeSpaces ()
  752. {
  753. tmpBuilder.Length = 0;
  754. for (int i = 0; i < valueCache.Length; i++)
  755. switch (valueCache [i]) {
  756. case '\r':
  757. if (i + 1 < valueCache.Length && valueCache [i + 1] == '\n')
  758. i++;
  759. goto case '\n';
  760. case '\t':
  761. case '\n':
  762. tmpBuilder.Append (' ');
  763. break;
  764. default:
  765. tmpBuilder.Append (valueCache [i]);
  766. break;
  767. }
  768. valueCache = tmpBuilder.ToString ();
  769. }
  770. }
  771. private XmlTokenInfo cursorToken;
  772. private XmlTokenInfo currentToken;
  773. private XmlAttributeTokenInfo currentAttributeToken;
  774. private XmlTokenInfo currentAttributeValueToken;
  775. private XmlAttributeTokenInfo [] attributeTokens = new XmlAttributeTokenInfo [10];
  776. private XmlTokenInfo [] attributeValueTokens = new XmlTokenInfo [10];
  777. private int currentAttribute;
  778. private int currentAttributeValue;
  779. private int attributeCount;
  780. private XmlParserContext parserContext;
  781. private ReadState readState;
  782. private int depth;
  783. private int elementDepth;
  784. private bool depthUp;
  785. private bool popScope;
  786. private string [] elementNames;
  787. int elementNameStackPos;
  788. private bool allowMultipleRoot;
  789. private bool isStandalone;
  790. private bool returnEntityReference;
  791. private string entityReferenceName;
  792. private char [] nameBuffer;
  793. private int nameLength;
  794. private int nameCapacity;
  795. private const int initialNameCapacity = 32;
  796. private char [] valueBuffer;
  797. private int valueLength;
  798. private int valueCapacity;
  799. private const int initialValueCapacity = 256;
  800. private char [] currentTagBuffer;
  801. private int currentTagLength;
  802. private int currentTagCapacity;
  803. private const int initialCurrentTagCapacity = 256;
  804. private TextReader reader;
  805. private char [] peekChars;
  806. private int peekCharsIndex;
  807. private int peekCharsLength;
  808. private const int peekCharCapacity = 1024;
  809. private int line;
  810. private int column;
  811. private int currentLinkedNodeLineNumber;
  812. private int currentLinkedNodeLinePosition;
  813. private bool useProceedingLineInfo;
  814. private XmlNodeType startNodeType;
  815. // State machine attribute.
  816. // XmlDeclaration: after the first node.
  817. // DocumentType: after doctypedecl
  818. // Element: inside document element
  819. // EndElement: after document element
  820. private XmlNodeType currentState;
  821. // For ReadChars()/ReadBase64()/ReadBinHex()
  822. private bool shouldSkipUntilEndTag;
  823. private byte [] base64Cache = new byte [3];
  824. private int base64CacheStartsAt;
  825. // These values are never re-initialized.
  826. private bool namespaces = true;
  827. private WhitespaceHandling whitespaceHandling = WhitespaceHandling.All;
  828. private XmlResolver resolver = new XmlUrlResolver ();
  829. private bool normalization = false;
  830. private bool prohibitDtd = false;
  831. private void Init ()
  832. {
  833. currentToken = new XmlTokenInfo (this, true);
  834. cursorToken = currentToken;
  835. currentAttribute = -1;
  836. currentAttributeValue = -1;
  837. attributeCount = 0;
  838. readState = ReadState.Initial;
  839. allowMultipleRoot = false;
  840. depth = 0;
  841. elementDepth = 0;
  842. depthUp = false;
  843. popScope = allowMultipleRoot = false;
  844. elementNames = new string [10];
  845. elementNameStackPos = 0;
  846. isStandalone = false;
  847. returnEntityReference = false;
  848. entityReferenceName = String.Empty;
  849. nameBuffer = new char [initialNameCapacity];
  850. nameLength = 0;
  851. nameCapacity = initialNameCapacity;
  852. valueBuffer = new char [initialValueCapacity];
  853. valueLength = 0;
  854. valueCapacity = initialValueCapacity;
  855. currentTagBuffer = new char [initialCurrentTagCapacity];
  856. currentTagLength = 0;
  857. currentTagCapacity = initialCurrentTagCapacity;
  858. peekCharsIndex = 0;
  859. peekCharsLength = 0;
  860. if (peekChars == null)
  861. peekChars = new char [peekCharCapacity];
  862. line = 1;
  863. column = 0;
  864. currentTagLength = 0;
  865. currentLinkedNodeLineNumber = currentLinkedNodeLinePosition = 0;
  866. useProceedingLineInfo = false;
  867. currentState = XmlNodeType.None;
  868. shouldSkipUntilEndTag = false;
  869. base64CacheStartsAt = -1;
  870. }
  871. private void InitializeContext (string url, XmlParserContext context, TextReader fragment, XmlNodeType fragType)
  872. {
  873. startNodeType = fragType;
  874. parserContext = context;
  875. if (context == null) {
  876. XmlNameTable nt = new NameTable ();
  877. parserContext = new XmlParserContext (nt,
  878. new XmlNamespaceManager (nt),
  879. String.Empty,
  880. XmlSpace.None);
  881. }
  882. if (url != null && url.Length > 0) {
  883. Uri uri = null;
  884. try {
  885. uri = new Uri (url);
  886. } catch (Exception) {
  887. string path = Path.GetFullPath ("./a");
  888. uri = new Uri (new Uri (path), url);
  889. }
  890. parserContext.BaseURI = uri.ToString ();
  891. }
  892. Init ();
  893. switch (fragType) {
  894. case XmlNodeType.Attribute:
  895. fragment = new StringReader (fragment.ReadToEnd ().Replace ("\"", "&quot;"));
  896. break;
  897. case XmlNodeType.Element:
  898. currentState = XmlNodeType.Element;
  899. allowMultipleRoot = true;
  900. break;
  901. case XmlNodeType.Document:
  902. break;
  903. default:
  904. throw new XmlException (String.Format ("NodeType {0} is not allowed to create XmlTextReader.", fragType));
  905. }
  906. reader = fragment;
  907. }
  908. // Use this method rather than setting the properties
  909. // directly so that all the necessary properties can
  910. // be changed in harmony with each other. Maybe the
  911. // fields should be in a seperate class to help enforce
  912. // this.
  913. private void SetProperties (
  914. XmlNodeType nodeType,
  915. string name,
  916. bool isEmptyElement,
  917. string value,
  918. bool clearAttributes)
  919. {
  920. SetProperties (currentToken, nodeType, name, isEmptyElement, value, clearAttributes);
  921. currentToken.LineNumber = this.currentLinkedNodeLineNumber;
  922. currentToken.LinePosition = this.currentLinkedNodeLinePosition;
  923. }
  924. private void SetProperties (
  925. XmlTokenInfo token,
  926. XmlNodeType nodeType,
  927. string name,
  928. bool isEmptyElement,
  929. string value,
  930. bool clearAttributes)
  931. {
  932. token.Clear ();
  933. token.NodeType = nodeType;
  934. token.Name = name;
  935. token.IsEmptyElement = isEmptyElement;
  936. token.Value = value;
  937. this.elementDepth = depth;
  938. if (clearAttributes)
  939. ClearAttributes ();
  940. token.FillNames ();
  941. }
  942. private void ClearAttributes ()
  943. {
  944. for (int i = 0; i < attributeCount; i++)
  945. attributeTokens [i].Clear ();
  946. attributeCount = 0;
  947. currentAttribute = -1;
  948. currentAttributeValue = -1;
  949. }
  950. private int PeekChar ()
  951. {
  952. if (peekCharsLength == peekCharsIndex) {
  953. if (!ReadTextReader ())
  954. return -1;
  955. return PeekChar ();
  956. }
  957. else
  958. return peekChars [peekCharsIndex];
  959. }
  960. private int ReadChar ()
  961. {
  962. int ch;
  963. if (peekCharsLength == peekCharsIndex) {
  964. if (!ReadTextReader ())
  965. return -1;
  966. return ReadChar ();
  967. }
  968. ch = peekChars [peekCharsIndex++];
  969. if (ch == '\n') {
  970. line++;
  971. column = 1;
  972. } else {
  973. column++;
  974. }
  975. if (currentState != XmlNodeType.Element)
  976. AppendCurrentTagChar (ch);
  977. return ch;
  978. }
  979. private bool ReadTextReader ()
  980. {
  981. peekCharsIndex = 0;
  982. peekCharsLength = reader.Read (peekChars, 0, peekCharCapacity);
  983. if (peekCharsLength == 0)
  984. return false;
  985. return true;
  986. }
  987. private string ExpandSurrogateChar (int ch)
  988. {
  989. if (ch < Char.MaxValue)
  990. return ((char) ch).ToString ();
  991. else {
  992. char [] tmp = new char [] {(char) (ch / 0x10000 + 0xD800 - 1), (char) (ch % 0x10000 + 0xDC00)};
  993. return new string (tmp);
  994. }
  995. }
  996. // This should really keep track of some state so
  997. // that it's not possible to have more than one document
  998. // element or text outside of the document element.
  999. private bool ReadContent ()
  1000. {
  1001. currentTagLength = 0;
  1002. if (popScope) {
  1003. parserContext.NamespaceManager.PopScope ();
  1004. popScope = false;
  1005. }
  1006. if (returnEntityReference)
  1007. SetEntityReferenceProperties ();
  1008. else {
  1009. int c = PeekChar ();
  1010. if (c == -1) {
  1011. readState = ReadState.EndOfFile;
  1012. ClearValueBuffer ();
  1013. SetProperties (
  1014. XmlNodeType.None, // nodeType
  1015. String.Empty, // name
  1016. false, // isEmptyElement
  1017. null, // value
  1018. true // clearAttributes
  1019. );
  1020. if (depth > 0)
  1021. throw new XmlException ("unexpected end of file. Current depth is " + depth);
  1022. return false;
  1023. } else {
  1024. switch ((char) c) {
  1025. case '<':
  1026. ReadChar ();
  1027. ReadTag ();
  1028. break;
  1029. case '\r': goto case ' ';
  1030. case '\n': goto case ' ';
  1031. case '\t': goto case ' ';
  1032. case ' ':
  1033. if (whitespaceHandling == WhitespaceHandling.All ||
  1034. whitespaceHandling == WhitespaceHandling.Significant)
  1035. ReadWhitespace ();
  1036. else {
  1037. SkipWhitespace ();
  1038. return ReadContent ();
  1039. }
  1040. break;
  1041. default:
  1042. ReadText (true);
  1043. break;
  1044. }
  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. if (prohibitDtd)
  1844. throw new XmlException (this as IXmlLineInfo,
  1845. "Document Type Declaration (DTD) is prohibited in this XML.");
  1846. switch (currentState) {
  1847. case XmlNodeType.DocumentType:
  1848. case XmlNodeType.Element:
  1849. case XmlNodeType.EndElement:
  1850. throw new XmlException (this as IXmlLineInfo,
  1851. "Document type cannot appear in this state.");
  1852. }
  1853. currentState = XmlNodeType.DocumentType;
  1854. string doctypeName = null;
  1855. string publicId = null;
  1856. string systemId = null;
  1857. int intSubsetStartLine = 0;
  1858. int intSubsetStartColumn = 0;
  1859. SkipWhitespace ();
  1860. doctypeName = ReadName ();
  1861. SkipWhitespace ();
  1862. switch(PeekChar ())
  1863. {
  1864. case 'S':
  1865. systemId = ReadSystemLiteral (true);
  1866. break;
  1867. case 'P':
  1868. publicId = ReadPubidLiteral ();
  1869. if (!SkipWhitespace ())
  1870. throw new XmlException (this as IXmlLineInfo,
  1871. "Whitespace is required between PUBLIC id and SYSTEM id.");
  1872. systemId = ReadSystemLiteral (false);
  1873. break;
  1874. }
  1875. SkipWhitespace ();
  1876. if(PeekChar () == '[')
  1877. {
  1878. // read markupdecl etc. or end of decl
  1879. ReadChar ();
  1880. intSubsetStartLine = this.LineNumber;
  1881. intSubsetStartColumn = this.LinePosition;
  1882. int startPos = currentTagLength;
  1883. ReadInternalSubset ();
  1884. int endPos = currentTagLength - 1;
  1885. parserContext.InternalSubset = new string (currentTagBuffer, startPos, endPos - startPos);
  1886. }
  1887. // end of DOCTYPE decl.
  1888. ExpectAfterWhitespace ('>');
  1889. GenerateDTDObjectModel (doctypeName, publicId,
  1890. systemId, parserContext.InternalSubset,
  1891. intSubsetStartLine, intSubsetStartColumn);
  1892. // set properties for <!DOCTYPE> node
  1893. SetProperties (
  1894. XmlNodeType.DocumentType, // nodeType
  1895. doctypeName, // name
  1896. false, // isEmptyElement
  1897. parserContext.InternalSubset, // value
  1898. true // clearAttributes
  1899. );
  1900. if (publicId != null)
  1901. AddAttribute ("PUBLIC", publicId);
  1902. if (systemId != null)
  1903. AddAttribute ("SYSTEM", systemId);
  1904. currentAttribute = currentAttributeValue = -1;
  1905. }
  1906. internal DTDObjectModel GenerateDTDObjectModel (string name, string publicId,
  1907. string systemId, string internalSubset)
  1908. {
  1909. return GenerateDTDObjectModel (name, publicId, systemId, internalSubset, 0, 0);
  1910. }
  1911. internal DTDObjectModel GenerateDTDObjectModel (string name, string publicId,
  1912. string systemId, string internalSubset, int intSubsetStartLine, int intSubsetStartColumn)
  1913. {
  1914. // now compile DTD
  1915. parserContext.Dtd = new DTDObjectModel (this.NameTable); // merges both internal and external subsets in the meantime,
  1916. DTD.BaseURI = BaseURI;
  1917. DTD.Name = name;
  1918. DTD.PublicId = publicId;
  1919. DTD.SystemId = systemId;
  1920. DTD.InternalSubset = internalSubset;
  1921. DTD.XmlResolver = resolver;
  1922. DTD.IsStandalone = isStandalone;
  1923. DTD.LineNumber = line;
  1924. DTD.LinePosition = column;
  1925. DTDReader dr = new DTDReader (DTD, intSubsetStartLine, intSubsetStartColumn);
  1926. dr.Normalization = this.normalization;
  1927. #if DTD_HANDLE_EVENTS
  1928. dr.ValidationEventHandler += new ValidationEventHandler (OnValidationEvent);
  1929. #endif
  1930. return dr.GenerateDTDObjectModel ();
  1931. }
  1932. private void OnValidationEvent (object o, ValidationEventArgs e)
  1933. {
  1934. #if DTD_HANDLE_EVENTS
  1935. if (ValidationEventHandler != null)
  1936. // Override object as this.
  1937. ValidationEventHandler (this, e);
  1938. #endif
  1939. }
  1940. private enum DtdInputState
  1941. {
  1942. Free = 1,
  1943. ElementDecl,
  1944. AttlistDecl,
  1945. EntityDecl,
  1946. NotationDecl,
  1947. PI,
  1948. Comment,
  1949. InsideSingleQuoted,
  1950. InsideDoubleQuoted,
  1951. }
  1952. private class DtdInputStateStack
  1953. {
  1954. Stack intern = new Stack ();
  1955. public DtdInputStateStack ()
  1956. {
  1957. Push (DtdInputState.Free);
  1958. }
  1959. public DtdInputState Peek ()
  1960. {
  1961. return (DtdInputState) intern.Peek ();
  1962. }
  1963. public DtdInputState Pop ()
  1964. {
  1965. return (DtdInputState) intern.Pop ();
  1966. }
  1967. public void Push (DtdInputState val)
  1968. {
  1969. intern.Push (val);
  1970. }
  1971. }
  1972. DtdInputStateStack stateStack = new DtdInputStateStack ();
  1973. DtdInputState State {
  1974. get { return stateStack.Peek (); }
  1975. }
  1976. // Simply read but not generate any result.
  1977. private void ReadInternalSubset ()
  1978. {
  1979. bool continueParse = true;
  1980. while (continueParse) {
  1981. switch (ReadChar ()) {
  1982. case ']':
  1983. switch (State) {
  1984. case DtdInputState.Free:
  1985. continueParse = false;
  1986. break;
  1987. case DtdInputState.InsideDoubleQuoted:
  1988. continue;
  1989. case DtdInputState.InsideSingleQuoted:
  1990. continue;
  1991. default:
  1992. throw new XmlException (this as IXmlLineInfo,"unexpected end of file at DTD.");
  1993. }
  1994. break;
  1995. case -1:
  1996. throw new XmlException (this as IXmlLineInfo,"unexpected end of file at DTD.");
  1997. case '<':
  1998. if (State == DtdInputState.InsideDoubleQuoted ||
  1999. State == DtdInputState.InsideSingleQuoted)
  2000. continue; // well-formed
  2001. switch (ReadChar ()) {
  2002. case '?':
  2003. stateStack.Push (DtdInputState.PI);
  2004. break;
  2005. case '!':
  2006. switch (ReadChar ()) {
  2007. case 'E':
  2008. switch (ReadChar ()) {
  2009. case 'L':
  2010. Expect ("EMENT");
  2011. stateStack.Push (DtdInputState.ElementDecl);
  2012. break;
  2013. case 'N':
  2014. Expect ("TITY");
  2015. stateStack.Push (DtdInputState.EntityDecl);
  2016. break;
  2017. default:
  2018. throw new XmlException (this as IXmlLineInfo,"unexpected token '<!E'.");
  2019. }
  2020. break;
  2021. case 'A':
  2022. Expect ("TTLIST");
  2023. stateStack.Push (DtdInputState.AttlistDecl);
  2024. break;
  2025. case 'N':
  2026. Expect ("OTATION");
  2027. stateStack.Push (DtdInputState.NotationDecl);
  2028. break;
  2029. case '-':
  2030. Expect ("-");
  2031. stateStack.Push (DtdInputState.Comment);
  2032. break;
  2033. }
  2034. break;
  2035. default:
  2036. throw new XmlException (this as IXmlLineInfo,"unexpected '>'.");
  2037. }
  2038. break;
  2039. case '\'':
  2040. if (State == DtdInputState.InsideSingleQuoted)
  2041. stateStack.Pop ();
  2042. else if (State != DtdInputState.InsideDoubleQuoted && State != DtdInputState.Comment)
  2043. stateStack.Push (DtdInputState.InsideSingleQuoted);
  2044. break;
  2045. case '"':
  2046. if (State == DtdInputState.InsideDoubleQuoted)
  2047. stateStack.Pop ();
  2048. else if (State != DtdInputState.InsideSingleQuoted && State != DtdInputState.Comment)
  2049. stateStack.Push (DtdInputState.InsideDoubleQuoted);
  2050. break;
  2051. case '>':
  2052. switch (State) {
  2053. case DtdInputState.ElementDecl:
  2054. goto case DtdInputState.NotationDecl;
  2055. case DtdInputState.AttlistDecl:
  2056. goto case DtdInputState.NotationDecl;
  2057. case DtdInputState.EntityDecl:
  2058. goto case DtdInputState.NotationDecl;
  2059. case DtdInputState.NotationDecl:
  2060. stateStack.Pop ();
  2061. break;
  2062. case DtdInputState.InsideDoubleQuoted:
  2063. continue;
  2064. case DtdInputState.InsideSingleQuoted:
  2065. continue; // well-formed
  2066. case DtdInputState.Comment:
  2067. continue;
  2068. default:
  2069. throw new XmlException (this as IXmlLineInfo,"unexpected token '>'");
  2070. }
  2071. break;
  2072. case '?':
  2073. if (State == DtdInputState.PI) {
  2074. if (ReadChar () == '>')
  2075. stateStack.Pop ();
  2076. }
  2077. break;
  2078. case '-':
  2079. if (State == DtdInputState.Comment) {
  2080. if (PeekChar () == '-') {
  2081. ReadChar ();
  2082. Expect ('>');
  2083. stateStack.Pop ();
  2084. }
  2085. }
  2086. break;
  2087. case '%':
  2088. if (State != DtdInputState.Free && State != DtdInputState.EntityDecl && State != DtdInputState.Comment && State != DtdInputState.InsideDoubleQuoted && State != DtdInputState.InsideSingleQuoted)
  2089. throw new XmlException (this as IXmlLineInfo,"Parameter Entity Reference cannot appear as a part of markupdecl (see XML spec 2.8).");
  2090. break;
  2091. }
  2092. }
  2093. }
  2094. // The reader is positioned on the first 'S' of "SYSTEM".
  2095. private string ReadSystemLiteral (bool expectSYSTEM)
  2096. {
  2097. if(expectSYSTEM) {
  2098. Expect ("SYSTEM");
  2099. if (!SkipWhitespace ())
  2100. throw new XmlException (this as IXmlLineInfo,
  2101. "Whitespace is required after 'SYSTEM'.");
  2102. }
  2103. else
  2104. SkipWhitespace ();
  2105. int quoteChar = ReadChar (); // apos or quot
  2106. int startPos = currentTagLength;
  2107. int c = 0;
  2108. ClearValueBuffer ();
  2109. while (c != quoteChar) {
  2110. c = ReadChar ();
  2111. if (c < 0)
  2112. throw new XmlException (this as IXmlLineInfo,"Unexpected end of stream in ExternalID.");
  2113. if (c != quoteChar)
  2114. AppendValueChar (c);
  2115. }
  2116. return CreateValueString ();
  2117. }
  2118. private string ReadPubidLiteral()
  2119. {
  2120. Expect ("PUBLIC");
  2121. if (!SkipWhitespace ())
  2122. throw new XmlException (this as IXmlLineInfo,
  2123. "Whitespace is required after 'PUBLIC'.");
  2124. int quoteChar = ReadChar ();
  2125. int startPos = currentTagLength;
  2126. int c = 0;
  2127. ClearValueBuffer ();
  2128. while(c != quoteChar)
  2129. {
  2130. c = ReadChar ();
  2131. if(c < 0) throw new XmlException (this as IXmlLineInfo,"Unexpected end of stream in ExternalID.");
  2132. if(c != quoteChar && !XmlChar.IsPubidChar (c))
  2133. throw new XmlException (this as IXmlLineInfo,"character '" + (char) c + "' not allowed for PUBLIC ID");
  2134. if (c != quoteChar)
  2135. AppendValueChar (c);
  2136. }
  2137. return CreateValueString ();
  2138. }
  2139. // The reader is positioned on the first character
  2140. // of the name.
  2141. private string ReadName ()
  2142. {
  2143. int ch = PeekChar ();
  2144. if (!XmlChar.IsFirstNameChar (ch))
  2145. throw new XmlException (this as IXmlLineInfo,String.Format (CultureInfo.InvariantCulture, "a name did not start with a legal character {0} ({1})", ch, (char) ch));
  2146. nameLength = 0;
  2147. AppendNameChar (ReadChar ());
  2148. while (XmlChar.IsNameChar (PeekChar ())) {
  2149. AppendNameChar (ReadChar ());
  2150. }
  2151. return CreateNameString ();
  2152. }
  2153. // Read the next character and compare it against the
  2154. // specified character.
  2155. private void Expect (int expected)
  2156. {
  2157. int ch = ReadChar ();
  2158. if (ch != expected) {
  2159. throw new XmlException (this as IXmlLineInfo,
  2160. String.Format (CultureInfo.InvariantCulture,
  2161. "expected '{0}' ({1:X}) but found '{2}' ({3:X})",
  2162. (char) expected,
  2163. expected,
  2164. (char) ch,
  2165. ch));
  2166. }
  2167. }
  2168. private void Expect (string expected)
  2169. {
  2170. int len = expected.Length;
  2171. for(int i=0; i< len; i++)
  2172. Expect (expected[i]);
  2173. }
  2174. private void ExpectAfterWhitespace (char c)
  2175. {
  2176. while (true) {
  2177. int i = ReadChar ();
  2178. if (i < 0x21 && XmlChar.IsWhitespace (i))
  2179. continue;
  2180. if (c != i)
  2181. throw new XmlException (this, String.Format (CultureInfo.InvariantCulture, "Expected {0}, but found {1} [{2}]", c, (char) i, i));
  2182. break;
  2183. }
  2184. }
  2185. // Does not consume the first non-whitespace character.
  2186. private bool SkipWhitespace ()
  2187. {
  2188. bool skipped = XmlChar.IsWhitespace (PeekChar ());
  2189. if (!skipped)
  2190. return false;
  2191. while (XmlChar.IsWhitespace (PeekChar ()))
  2192. ReadChar ();
  2193. return skipped;
  2194. }
  2195. private void ReadWhitespace ()
  2196. {
  2197. if (currentState == XmlNodeType.None)
  2198. currentState = XmlNodeType.XmlDeclaration;
  2199. ClearValueBuffer ();
  2200. int ch = PeekChar ();
  2201. do {
  2202. AppendValueChar (ReadChar ());
  2203. } while ((ch = PeekChar ()) != -1 && XmlChar.IsWhitespace (ch));
  2204. if (currentState == XmlNodeType.Element && ch != -1 && ch != '<')
  2205. ReadText (false);
  2206. else {
  2207. XmlNodeType nodeType = (this.XmlSpace == XmlSpace.Preserve) ?
  2208. XmlNodeType.SignificantWhitespace : XmlNodeType.Whitespace;
  2209. SetProperties (nodeType,
  2210. String.Empty,
  2211. false,
  2212. null, // value: create only when required
  2213. true);
  2214. }
  2215. return;
  2216. }
  2217. private byte GetBase64Byte (char ch)
  2218. {
  2219. switch (ch) {
  2220. case '+':
  2221. return 62;
  2222. case '/':
  2223. return 63;
  2224. case '=':
  2225. return 0;
  2226. default:
  2227. if (ch >= 'A' && ch <= 'Z')
  2228. return (byte) (ch - 'A');
  2229. else if (ch >= 'a' && ch <= 'z')
  2230. return (byte) (ch - 'a' + 26);
  2231. else if (ch >= '0' && ch <= '9')
  2232. return (byte) (ch - '0' + 52);
  2233. else
  2234. throw new XmlException ("Invalid Base64 character was found.");
  2235. }
  2236. }
  2237. // Returns -1 if it should throw an error.
  2238. private int ReadCharsInternal (char [] buffer, int offset, int length)
  2239. {
  2240. if (IsEmptyElement) {
  2241. Read ();
  2242. return 0;
  2243. }
  2244. shouldSkipUntilEndTag = true;
  2245. if (offset < 0)
  2246. throw new ArgumentOutOfRangeException ("offset", offset, "Offset must be non-negative integer.");
  2247. else if (length < 0)
  2248. throw new ArgumentOutOfRangeException ("length", length, "Length must be non-negative integer.");
  2249. else if (buffer.Length < offset + length)
  2250. throw new ArgumentOutOfRangeException ("buffer length is smaller than the sum of offset and length.");
  2251. if (NodeType != XmlNodeType.Element)
  2252. return 0;
  2253. int bufIndex = offset;
  2254. for (int i = 0; i < length; i++) {
  2255. int c = PeekChar ();
  2256. switch (c) {
  2257. case -1:
  2258. throw new XmlException (this as IXmlLineInfo, "Unexpected end of xml.");
  2259. case '<':
  2260. ReadChar ();
  2261. if (PeekChar () != '/') {
  2262. buffer [bufIndex++] = '<';
  2263. continue;
  2264. }
  2265. // Seems to skip immediate EndElement
  2266. Expect ('/');
  2267. if (depthUp) {
  2268. depth++;
  2269. depthUp = false;
  2270. }
  2271. ReadEndTag();
  2272. shouldSkipUntilEndTag = false;
  2273. Read ();
  2274. return i;
  2275. default:
  2276. ReadChar ();
  2277. if (c < Char.MaxValue)
  2278. buffer [bufIndex++] = (char) c;
  2279. else {
  2280. buffer [bufIndex++] = (char) (c / 0x10000 + 0xD800 - 1);
  2281. buffer [bufIndex++] = (char) (c % 0x10000 + 0xDC00);
  2282. }
  2283. break;
  2284. }
  2285. }
  2286. return length;
  2287. }
  2288. private bool ReadUntilEndTag ()
  2289. {
  2290. int ch;
  2291. do {
  2292. ch = ReadChar ();
  2293. switch (ch) {
  2294. case -1:
  2295. throw new XmlException (this as IXmlLineInfo,
  2296. "Unexpected end of xml.");
  2297. case '<':
  2298. if (PeekChar () != '/')
  2299. continue;
  2300. ReadChar ();
  2301. string name = ReadName ();
  2302. if (name != elementNames [elementNameStackPos - 1])
  2303. continue;
  2304. Expect ('>');
  2305. depth--;
  2306. elementNames [--elementNameStackPos] = null;
  2307. return Read ();
  2308. }
  2309. } while (true);
  2310. }
  2311. #endregion
  2312. }
  2313. }