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. [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. int c = PeekChar ();
  1013. if (c == -1) {
  1014. readState = ReadState.EndOfFile;
  1015. ClearValueBuffer ();
  1016. SetProperties (
  1017. XmlNodeType.None, // nodeType
  1018. String.Empty, // name
  1019. false, // isEmptyElement
  1020. null, // value
  1021. true // clearAttributes
  1022. );
  1023. if (depth > 0)
  1024. throw new XmlException ("unexpected end of file. Current depth is " + depth);
  1025. return false;
  1026. } else {
  1027. switch ((char) c) {
  1028. case '<':
  1029. ReadChar ();
  1030. ReadTag ();
  1031. break;
  1032. case '\r': goto case ' ';
  1033. case '\n': goto case ' ';
  1034. case '\t': goto case ' ';
  1035. case ' ':
  1036. if (whitespaceHandling == WhitespaceHandling.All ||
  1037. whitespaceHandling == WhitespaceHandling.Significant)
  1038. ReadWhitespace ();
  1039. else {
  1040. SkipWhitespace ();
  1041. return ReadContent ();
  1042. }
  1043. break;
  1044. default:
  1045. ReadText (true);
  1046. break;
  1047. }
  1048. }
  1049. }
  1050. return this.ReadState != ReadState.EndOfFile;
  1051. }
  1052. private void SetEntityReferenceProperties ()
  1053. {
  1054. DTDEntityDeclaration decl = DTD != null ? DTD.EntityDecls [entityReferenceName] : null;
  1055. if (this.isStandalone)
  1056. if (DTD == null || decl == null || !decl.IsInternalSubset)
  1057. throw new XmlException (this as IXmlLineInfo,
  1058. "Standalone document must not contain any references to an non-internally declared entity.");
  1059. if (decl != null && decl.NotationName != null)
  1060. throw new XmlException (this as IXmlLineInfo,
  1061. "Reference to any unparsed entities is not allowed here.");
  1062. ClearValueBuffer ();
  1063. SetProperties (
  1064. XmlNodeType.EntityReference, // nodeType
  1065. entityReferenceName, // name
  1066. false, // isEmptyElement
  1067. null, // value
  1068. true // clearAttributes
  1069. );
  1070. returnEntityReference = false;
  1071. entityReferenceName = String.Empty;
  1072. }
  1073. // The leading '<' has already been consumed.
  1074. private void ReadTag ()
  1075. {
  1076. switch (PeekChar ())
  1077. {
  1078. case '/':
  1079. ReadChar ();
  1080. ReadEndTag ();
  1081. break;
  1082. case '?':
  1083. ReadChar ();
  1084. ReadProcessingInstruction ();
  1085. break;
  1086. case '!':
  1087. ReadChar ();
  1088. ReadDeclaration ();
  1089. break;
  1090. default:
  1091. ReadStartTag ();
  1092. break;
  1093. }
  1094. }
  1095. // The leading '<' has already been consumed.
  1096. private void ReadStartTag ()
  1097. {
  1098. if (currentState == XmlNodeType.EndElement)
  1099. throw new XmlException (this as IXmlLineInfo,
  1100. "Multiple document element was detected.");
  1101. currentState = XmlNodeType.Element;
  1102. parserContext.NamespaceManager.PushScope ();
  1103. string name = ReadName ();
  1104. if (currentState == XmlNodeType.EndElement)
  1105. throw new XmlException (this as IXmlLineInfo,"document has terminated, cannot open new element");
  1106. bool isEmptyElement = false;
  1107. ClearAttributes ();
  1108. SkipWhitespace ();
  1109. if (XmlChar.IsFirstNameChar (PeekChar ()))
  1110. ReadAttributes (false);
  1111. cursorToken = this.currentToken;
  1112. // fill namespaces
  1113. for (int i = 0; i < attributeCount; i++)
  1114. attributeTokens [i].FillNames ();
  1115. // quick name check
  1116. for (int i = 0; i < attributeCount; i++) {
  1117. for (int j = i + 1; j < attributeCount; j++)
  1118. if (Object.ReferenceEquals (attributeTokens [i].Name, attributeTokens [j].Name) ||
  1119. (Object.ReferenceEquals (attributeTokens [i].LocalName, attributeTokens [j].LocalName) &&
  1120. Object.ReferenceEquals (attributeTokens [i].NamespaceURI, attributeTokens [j].NamespaceURI)))
  1121. throw new XmlException (this as IXmlLineInfo,
  1122. "Attribute name and qualified name must be identical.");
  1123. }
  1124. string baseUri = GetAttribute ("xml:base");
  1125. if (baseUri != null) {
  1126. if (this.resolver != null)
  1127. parserContext.BaseURI = resolver.ResolveUri (new Uri (BaseURI), baseUri).ToString ();
  1128. else
  1129. parserContext.BaseURI = baseUri;
  1130. }
  1131. string xmlLang = GetAttribute ("xml:lang");
  1132. if (xmlLang != null)
  1133. parserContext.XmlLang = xmlLang;
  1134. string xmlSpaceAttr = GetAttribute ("xml:space");
  1135. if (xmlSpaceAttr != null) {
  1136. if (xmlSpaceAttr == "preserve")
  1137. parserContext.XmlSpace = XmlSpace.Preserve;
  1138. else if (xmlSpaceAttr == "default")
  1139. parserContext.XmlSpace = XmlSpace.Default;
  1140. else
  1141. throw new XmlException (this as IXmlLineInfo,String.Format ("Invalid xml:space value: {0}", xmlSpaceAttr));
  1142. }
  1143. if (PeekChar () == '/') {
  1144. ReadChar ();
  1145. isEmptyElement = true;
  1146. popScope = true;
  1147. }
  1148. else {
  1149. depthUp = true;
  1150. PushElementName (name);
  1151. parserContext.PushScope ();
  1152. }
  1153. Expect ('>');
  1154. SetProperties (
  1155. XmlNodeType.Element, // nodeType
  1156. name, // name
  1157. isEmptyElement, // isEmptyElement
  1158. null, // value
  1159. false // clearAttributes
  1160. );
  1161. if (LookupNamespace (Prefix) == null)
  1162. throw new XmlException (String.Format ("'{0}' is undeclared namespace.", Prefix));
  1163. try {
  1164. for (int i = 0; i < attributeCount; i++) {
  1165. MoveToAttribute (i);
  1166. if (LookupNamespace (Prefix) == null)
  1167. throw new XmlException (String.Format ("'{0}' is undeclared namespace.", Prefix));
  1168. }
  1169. } finally {
  1170. MoveToElement ();
  1171. }
  1172. if (IsEmptyElement)
  1173. CheckCurrentStateUpdate ();
  1174. }
  1175. private void PushElementName (string name)
  1176. {
  1177. if (elementNames.Length == elementNameStackPos) {
  1178. string [] newArray = new string [elementNames.Length * 2];
  1179. Array.Copy (elementNames, 0, newArray, 0, elementNameStackPos);
  1180. elementNames = newArray;
  1181. }
  1182. elementNames [elementNameStackPos++] = name;
  1183. }
  1184. // The reader is positioned on the first character
  1185. // of the element's name.
  1186. private void ReadEndTag ()
  1187. {
  1188. if (currentState != XmlNodeType.Element)
  1189. throw new XmlException (this as IXmlLineInfo,
  1190. "End tag cannot appear in this state.");
  1191. string name = ReadName ();
  1192. if (elementNameStackPos == 0)
  1193. throw new XmlException (this as IXmlLineInfo,"closing element without matching opening element");
  1194. string expected = elementNames [--elementNameStackPos];
  1195. if (expected != name)
  1196. throw new XmlException (this as IXmlLineInfo,String.Format ("unmatched closing element: expected {0} but found {1}", expected, name));
  1197. parserContext.PopScope ();
  1198. ExpectAfterWhitespace ('>');
  1199. --depth;
  1200. SetProperties (
  1201. XmlNodeType.EndElement, // nodeType
  1202. name, // name
  1203. false, // isEmptyElement
  1204. null, // value
  1205. true // clearAttributes
  1206. );
  1207. popScope = true;
  1208. CheckCurrentStateUpdate ();
  1209. }
  1210. private void CheckCurrentStateUpdate ()
  1211. {
  1212. if (depth == 0 && !allowMultipleRoot && (IsEmptyElement || NodeType == XmlNodeType.EndElement))
  1213. currentState = XmlNodeType.EndElement;
  1214. }
  1215. private void AppendNameChar (int ch)
  1216. {
  1217. if (nameLength == nameCapacity)
  1218. ExpandNameCapacity ();
  1219. if (ch < Char.MaxValue)
  1220. nameBuffer [nameLength++] = (char) ch;
  1221. else {
  1222. nameBuffer [nameLength++] = (char) (ch / 0x10000 + 0xD800 - 1);
  1223. if (nameLength == nameCapacity)
  1224. ExpandNameCapacity ();
  1225. nameBuffer [nameLength++] = (char) (ch % 0x10000 + 0xDC00);
  1226. }
  1227. }
  1228. private void ExpandNameCapacity ()
  1229. {
  1230. nameCapacity = nameCapacity * 2;
  1231. char [] oldNameBuffer = nameBuffer;
  1232. nameBuffer = new char [nameCapacity];
  1233. Array.Copy (oldNameBuffer, nameBuffer, nameLength);
  1234. }
  1235. private string CreateNameString ()
  1236. {
  1237. return parserContext.NameTable.Add (nameBuffer, 0, nameLength);
  1238. }
  1239. private void AppendValueChar (int ch)
  1240. {
  1241. if (valueLength == valueCapacity)
  1242. ExpandValueCapacity ();
  1243. if (ch < Char.MaxValue)
  1244. valueBuffer [valueLength++] = (char) ch;
  1245. else {
  1246. valueBuffer [valueLength++] = (char) (ch / 0x10000 + 0xD800 - 1);
  1247. if (valueLength == valueCapacity)
  1248. ExpandValueCapacity ();
  1249. valueBuffer [valueLength++] = (char) (ch % 0x10000 + 0xDC00);
  1250. }
  1251. }
  1252. private void ExpandValueCapacity ()
  1253. {
  1254. valueCapacity = valueCapacity * 2;
  1255. char [] oldValueBuffer = valueBuffer;
  1256. valueBuffer = new char [valueCapacity];
  1257. Array.Copy (oldValueBuffer, valueBuffer, valueLength);
  1258. }
  1259. private string CreateValueString ()
  1260. {
  1261. return new string (valueBuffer, 0, valueLength);
  1262. }
  1263. private void ClearValueBuffer ()
  1264. {
  1265. valueLength = 0;
  1266. }
  1267. private void AppendCurrentTagChar (int ch)
  1268. {
  1269. if (currentTagLength == currentTagCapacity)
  1270. ExpandCurrentTagCapacity ();
  1271. if (ch < Char.MaxValue)
  1272. currentTagBuffer [currentTagLength++] = (char) ch;
  1273. else {
  1274. currentTagBuffer [currentTagLength++] = (char) (ch / 0x10000 + 0xD800 - 1);
  1275. if (currentTagLength == currentTagCapacity)
  1276. ExpandCurrentTagCapacity ();
  1277. currentTagBuffer [currentTagLength++] = (char) (ch % 0x10000 + 0xDC00);
  1278. }
  1279. }
  1280. private void ExpandCurrentTagCapacity ()
  1281. {
  1282. currentTagCapacity = currentTagCapacity * 2;
  1283. char [] oldCurrentTagBuffer = currentTagBuffer;
  1284. currentTagBuffer = new char [currentTagCapacity];
  1285. Array.Copy (oldCurrentTagBuffer, currentTagBuffer, currentTagLength);
  1286. }
  1287. private string CreateCurrentTagString ()
  1288. {
  1289. return new string (currentTagBuffer, 0, currentTagLength);
  1290. }
  1291. private void ClearCurrentTagBuffer ()
  1292. {
  1293. currentTagLength = 0;
  1294. }
  1295. // The reader is positioned on the first character
  1296. // of the text.
  1297. private void ReadText (bool notWhitespace)
  1298. {
  1299. if (currentState != XmlNodeType.Element)
  1300. throw new XmlException (this as IXmlLineInfo,
  1301. "Text node cannot appear in this state.");
  1302. if (notWhitespace)
  1303. ClearValueBuffer ();
  1304. int ch = PeekChar ();
  1305. bool previousWasCloseBracket = false;
  1306. while (ch != '<' && ch != -1) {
  1307. if (ch == '&') {
  1308. ReadChar ();
  1309. ch = ReadReference (false);
  1310. if (returnEntityReference) // Returns -1 if char validation should not be done
  1311. break;
  1312. }
  1313. else {
  1314. if (XmlChar.IsInvalid (ch))
  1315. throw new XmlException (this, "Not allowed character was found.");
  1316. ch = ReadChar ();
  1317. }
  1318. AppendValueChar (ch);
  1319. // Block "]]>"
  1320. if (ch == ']') {
  1321. if (previousWasCloseBracket)
  1322. if (PeekChar () == '>')
  1323. throw new XmlException (this as IXmlLineInfo,
  1324. "Inside text content, character sequence ']]>' is not allowed.");
  1325. previousWasCloseBracket = true;
  1326. }
  1327. else if (previousWasCloseBracket)
  1328. previousWasCloseBracket = false;
  1329. ch = PeekChar ();
  1330. notWhitespace = true;
  1331. }
  1332. if (returnEntityReference && valueLength == 0) {
  1333. SetEntityReferenceProperties ();
  1334. } else {
  1335. XmlNodeType nodeType = notWhitespace ? XmlNodeType.Text :
  1336. this.XmlSpace == XmlSpace.Preserve ? XmlNodeType.SignificantWhitespace : XmlNodeType.Whitespace;
  1337. SetProperties (
  1338. nodeType, // nodeType
  1339. String.Empty, // name
  1340. false, // isEmptyElement
  1341. null, // value: create only when required
  1342. true // clearAttributes
  1343. );
  1344. }
  1345. }
  1346. // The leading '&' has already been consumed.
  1347. // Returns true if the entity reference isn't a simple
  1348. // character reference or one of the predefined entities.
  1349. // This allows the ReadText method to break so that the
  1350. // next call to Read will return the EntityReference node.
  1351. private int ReadReference (bool ignoreEntityReferences)
  1352. {
  1353. if (PeekChar () == '#') {
  1354. ReadChar ();
  1355. return ReadCharacterReference ();
  1356. } else
  1357. return ReadEntityReference (ignoreEntityReferences);
  1358. }
  1359. private int ReadCharacterReference ()
  1360. {
  1361. int value = 0;
  1362. if (PeekChar () == 'x') {
  1363. ReadChar ();
  1364. while (PeekChar () != ';' && PeekChar () != -1) {
  1365. int ch = ReadChar ();
  1366. if (ch >= '0' && ch <= '9')
  1367. value = (value << 4) + ch - '0';
  1368. else if (ch >= 'A' && ch <= 'F')
  1369. value = (value << 4) + ch - 'A' + 10;
  1370. else if (ch >= 'a' && ch <= 'f')
  1371. value = (value << 4) + ch - 'a' + 10;
  1372. else
  1373. throw new XmlException (this as IXmlLineInfo,
  1374. String.Format (CultureInfo.InvariantCulture,
  1375. "invalid hexadecimal digit: {0} (#x{1:X})",
  1376. (char) ch,
  1377. ch));
  1378. }
  1379. } else {
  1380. while (PeekChar () != ';' && PeekChar () != -1) {
  1381. int ch = ReadChar ();
  1382. if (ch >= '0' && ch <= '9')
  1383. value = value * 10 + ch - '0';
  1384. else
  1385. throw new XmlException (this as IXmlLineInfo,
  1386. String.Format (CultureInfo.InvariantCulture,
  1387. "invalid decimal digit: {0} (#x{1:X})",
  1388. (char) ch,
  1389. ch));
  1390. }
  1391. }
  1392. ReadChar (); // ';'
  1393. // There is no way to save surrogate pairs...
  1394. if (normalization && XmlChar.IsInvalid (value))
  1395. throw new XmlException (this as IXmlLineInfo,
  1396. "Referenced character was not allowed in XML.");
  1397. return value;
  1398. }
  1399. // Returns -1 if it should not be validated.
  1400. // Real EOF must not be detected here.
  1401. private int ReadEntityReference (bool ignoreEntityReferences)
  1402. {
  1403. string name = ReadName ();
  1404. Expect (';');
  1405. int predefined = XmlChar.GetPredefinedEntity (name);
  1406. if (predefined >= 0)
  1407. return predefined;
  1408. else {
  1409. if (ignoreEntityReferences) {
  1410. AppendValueChar ('&');
  1411. for (int i = 0; i < name.Length; i++)
  1412. AppendValueChar (name [i]);
  1413. AppendValueChar (';');
  1414. } else {
  1415. returnEntityReference = true;
  1416. entityReferenceName = name;
  1417. }
  1418. }
  1419. return -1;
  1420. }
  1421. // The reader is positioned on the first character of
  1422. // the attribute name.
  1423. private void ReadAttributes (bool isXmlDecl)
  1424. {
  1425. int peekChar = -1;
  1426. bool requireWhitespace = false;
  1427. currentAttribute = -1;
  1428. currentAttributeValue = -1;
  1429. do {
  1430. if (!SkipWhitespace () && requireWhitespace)
  1431. throw new XmlException ("Unexpected token. Name is required here.");
  1432. IncrementAttributeToken ();
  1433. currentAttributeToken.LineNumber = line;
  1434. currentAttributeToken.LinePosition = column;
  1435. currentAttributeToken.LocalName =
  1436. currentAttributeToken.Name = ReadName ();
  1437. ExpectAfterWhitespace ('=');
  1438. SkipWhitespace ();
  1439. ReadAttributeValueTokens (-1);
  1440. attributeCount++;
  1441. if (currentAttributeToken.Name == "xmlns")
  1442. parserContext.NamespaceManager.AddNamespace (String.Empty, GetAttribute (currentAttribute));
  1443. else if (currentAttributeToken.Name.StartsWith ("xmlns:")) {
  1444. string nsPrefix = currentAttributeToken.Name.Substring (6);
  1445. parserContext.NamespaceManager.AddNamespace (nsPrefix, GetAttribute (currentAttribute));
  1446. }
  1447. if (!SkipWhitespace ())
  1448. requireWhitespace = true;
  1449. peekChar = PeekChar ();
  1450. if (isXmlDecl) {
  1451. if (peekChar == '?')
  1452. break;
  1453. }
  1454. else if (peekChar == '/' || peekChar == '>')
  1455. break;
  1456. } while (peekChar != -1);
  1457. currentAttribute = -1;
  1458. currentAttributeValue = -1;
  1459. }
  1460. private void AddAttribute (string name, string value)
  1461. {
  1462. IncrementAttributeToken ();
  1463. XmlAttributeTokenInfo ati = attributeTokens [currentAttribute];
  1464. ati.Name = "SYSTEM";
  1465. ati.FillNames ();
  1466. IncrementAttributeValueToken ();
  1467. XmlTokenInfo vti = attributeValueTokens [currentAttributeValue];
  1468. vti.Value = value;
  1469. SetProperties (vti, XmlNodeType.Text, String.Empty, false, value, false);
  1470. attributeCount++;
  1471. }
  1472. private void IncrementAttributeToken ()
  1473. {
  1474. currentAttribute++;
  1475. if (attributeTokens.Length == currentAttribute) {
  1476. XmlAttributeTokenInfo [] newArray =
  1477. new XmlAttributeTokenInfo [attributeTokens.Length * 2];
  1478. attributeTokens.CopyTo (newArray, 0);
  1479. attributeTokens = newArray;
  1480. }
  1481. if (attributeTokens [currentAttribute] == null)
  1482. attributeTokens [currentAttribute] = new XmlAttributeTokenInfo (this);
  1483. currentAttributeToken = attributeTokens [currentAttribute];
  1484. currentAttributeToken.Clear ();
  1485. }
  1486. private void IncrementAttributeValueToken ()
  1487. {
  1488. ClearValueBuffer ();
  1489. currentAttributeValue++;
  1490. if (attributeValueTokens.Length == currentAttributeValue) {
  1491. XmlTokenInfo [] newArray = new XmlTokenInfo [attributeValueTokens.Length * 2];
  1492. attributeValueTokens.CopyTo (newArray, 0);
  1493. attributeValueTokens = newArray;
  1494. }
  1495. if (attributeValueTokens [currentAttributeValue] == null)
  1496. attributeValueTokens [currentAttributeValue] = new XmlTokenInfo (this, false);
  1497. currentAttributeValueToken = attributeValueTokens [currentAttributeValue];
  1498. currentAttributeValueToken.Clear ();
  1499. }
  1500. // LAMESPEC: Orthodox XML reader should normalize attribute values
  1501. private void ReadAttributeValueTokens (int dummyQuoteChar)
  1502. {
  1503. int quoteChar = (dummyQuoteChar < 0) ? ReadChar () : dummyQuoteChar;
  1504. if (quoteChar != '\'' && quoteChar != '\"')
  1505. throw new XmlException (this as IXmlLineInfo,"an attribute value was not quoted");
  1506. currentAttributeToken.QuoteChar = (char) quoteChar;
  1507. IncrementAttributeValueToken ();
  1508. currentAttributeToken.ValueTokenStartIndex = currentAttributeValue;
  1509. currentAttributeValueToken.LineNumber = line;
  1510. currentAttributeValueToken.LinePosition = column;
  1511. bool incrementToken = false;
  1512. bool isNewToken = true;
  1513. bool loop = true;
  1514. int ch = 0;
  1515. while (loop) {
  1516. ch = ReadChar ();
  1517. if (ch == quoteChar)
  1518. break;
  1519. if (incrementToken) {
  1520. IncrementAttributeValueToken ();
  1521. currentAttributeValueToken.LineNumber = line;
  1522. currentAttributeValueToken.LinePosition = column;
  1523. incrementToken = false;
  1524. isNewToken = true;
  1525. }
  1526. switch (ch)
  1527. {
  1528. case '<':
  1529. throw new XmlException (this as IXmlLineInfo,"attribute values cannot contain '<'");
  1530. case -1:
  1531. if (dummyQuoteChar < 0)
  1532. throw new XmlException (this as IXmlLineInfo,"unexpected end of file in an attribute value");
  1533. else // Attribute value constructor.
  1534. loop = false;
  1535. break;
  1536. case '&':
  1537. int startPosition = currentTagLength - 1;
  1538. if (PeekChar () == '#') {
  1539. ReadChar ();
  1540. ch = ReadCharacterReference ();
  1541. if (normalization && XmlChar.IsInvalid (ch))
  1542. throw new XmlException (this as IXmlLineInfo,
  1543. "Not allowed character was found.");
  1544. AppendValueChar (ch);
  1545. break;
  1546. }
  1547. // Check XML 1.0 section 3.1 WFC.
  1548. string entName = ReadName ();
  1549. Expect (';');
  1550. int predefined = XmlChar.GetPredefinedEntity (entName);
  1551. if (predefined < 0) {
  1552. CheckAttributeEntityReferenceWFC (entName);
  1553. currentAttributeValueToken.Value = CreateValueString ();
  1554. currentAttributeValueToken.NodeType = XmlNodeType.Text;
  1555. if (!isNewToken)
  1556. IncrementAttributeValueToken ();
  1557. currentAttributeValueToken.Name = entName;
  1558. currentAttributeValueToken.Value = String.Empty;
  1559. currentAttributeValueToken.NodeType = XmlNodeType.EntityReference;
  1560. incrementToken = true;
  1561. }
  1562. else
  1563. AppendValueChar (predefined);
  1564. break;
  1565. default:
  1566. if (normalization && XmlChar.IsInvalid (ch))
  1567. throw new XmlException (this, "Invalid character was found.");
  1568. AppendValueChar (ch);
  1569. break;
  1570. }
  1571. isNewToken = false;
  1572. }
  1573. if (!incrementToken) {
  1574. currentAttributeValueToken.Value = CreateValueString ();
  1575. currentAttributeValueToken.NodeType = XmlNodeType.Text;
  1576. }
  1577. currentAttributeToken.ValueTokenEndIndex = currentAttributeValue;
  1578. }
  1579. private void CheckAttributeEntityReferenceWFC (string entName)
  1580. {
  1581. DTDEntityDeclaration entDecl =
  1582. DTD == null ? null : DTD.EntityDecls [entName];
  1583. if (DTD != null && resolver != null && entDecl == null)
  1584. throw new XmlException (this, "Referenced entity does not exist.");
  1585. if (entDecl == null)
  1586. return;
  1587. if (entDecl.HasExternalReference)
  1588. throw new XmlException (this, "Reference to external entities is not allowed in the value of an attribute.");
  1589. if (isStandalone && !entDecl.IsInternalSubset)
  1590. throw new XmlException (this, "Reference to external entities is not allowed in the internal subset.");
  1591. if (entDecl.EntityValue.IndexOf ('<') >= 0)
  1592. throw new XmlException (this, "Attribute must not contain character '<' either directly or indirectly by way of entity references.");
  1593. }
  1594. // The reader is positioned on the first character
  1595. // of the target.
  1596. //
  1597. // It may be xml declaration or processing instruction.
  1598. private void ReadProcessingInstruction ()
  1599. {
  1600. string target = ReadName ();
  1601. if (target == "xml") {
  1602. ReadXmlDeclaration ();
  1603. return;
  1604. } else if (target.ToLower (CultureInfo.InvariantCulture) == "xml")
  1605. throw new XmlException (this as IXmlLineInfo,
  1606. "Not allowed processing instruction name which starts with 'X', 'M', 'L' was found.");
  1607. if (currentState == XmlNodeType.None)
  1608. currentState = XmlNodeType.XmlDeclaration;
  1609. if (!SkipWhitespace ())
  1610. if (PeekChar () != '?')
  1611. throw new XmlException (this as IXmlLineInfo,
  1612. "Invalid processing instruction name was found.");
  1613. ClearValueBuffer ();
  1614. while (PeekChar () != -1) {
  1615. int ch = ReadChar ();
  1616. if (ch == '?' && PeekChar () == '>') {
  1617. ReadChar ();
  1618. break;
  1619. }
  1620. if (normalization && XmlChar.IsInvalid (ch))
  1621. throw new XmlException (this, "Invalid character was found.");
  1622. AppendValueChar (ch);
  1623. }
  1624. SetProperties (
  1625. XmlNodeType.ProcessingInstruction, // nodeType
  1626. target, // name
  1627. false, // isEmptyElement
  1628. null, // value: create only when required
  1629. true // clearAttributes
  1630. );
  1631. }
  1632. // The reader is positioned after "<?xml "
  1633. private void ReadXmlDeclaration ()
  1634. {
  1635. if (currentState != XmlNodeType.None) {
  1636. throw new XmlException (this as IXmlLineInfo,
  1637. "XML declaration cannot appear in this state.");
  1638. }
  1639. currentState = XmlNodeType.XmlDeclaration;
  1640. ClearAttributes ();
  1641. ReadAttributes (true); // They must have "version."
  1642. string version = GetAttribute ("version");
  1643. string message = null;
  1644. if (attributeTokens [0].Name != "version" || version != "1.0")
  1645. message = "Version 1.0 declaration is required in XML Declaration.";
  1646. else if (attributeCount > 1 &&
  1647. (attributeTokens [1].Name != "encoding" &&
  1648. attributeTokens [1].Name != "standalone"))
  1649. message = "Invalid Xml Declaration markup was found.";
  1650. else if (attributeCount > 2 && attributeTokens [2].Name != "standalone")
  1651. message = "Invalid Xml Declaration markup was found.";
  1652. string sa = GetAttribute ("standalone");
  1653. if (sa != null && sa != "yes" && sa != "no")
  1654. message = "Only 'yes' or 'no' is allowed for standalone.";
  1655. this.isStandalone = (sa == "yes");
  1656. if (message != null)
  1657. throw new XmlException (this as IXmlLineInfo, message);
  1658. SetProperties (
  1659. XmlNodeType.XmlDeclaration, // nodeType
  1660. "xml", // name
  1661. false, // isEmptyElement
  1662. new string (currentTagBuffer, 6, currentTagLength - 6), // value
  1663. false // clearAttributes
  1664. );
  1665. Expect ("?>");
  1666. }
  1667. internal void SkipTextDeclaration ()
  1668. {
  1669. this.currentState = XmlNodeType.Element;
  1670. if (PeekChar () != '<')
  1671. return;
  1672. ReadChar ();
  1673. if (PeekChar () != '?') {
  1674. peekCharsIndex = 0;
  1675. return;
  1676. }
  1677. ReadChar ();
  1678. while (peekCharsIndex < 6) {
  1679. if (PeekChar () < 0)
  1680. break;
  1681. else
  1682. ReadChar ();
  1683. }
  1684. if (new string (peekChars, 2, 4) != "xml ") {
  1685. if (new string (peekChars, 2, 3).ToLower (CultureInfo.InvariantCulture) == "xml") {
  1686. throw new XmlException (this as IXmlLineInfo,
  1687. "Processing instruction name must not be character sequence 'X' 'M' 'L' with case insensitivity.");
  1688. }
  1689. peekCharsIndex = 0;
  1690. return;
  1691. }
  1692. SkipWhitespace ();
  1693. // version decl
  1694. if (PeekChar () == 'v') {
  1695. Expect ("version");
  1696. ExpectAfterWhitespace ('=');
  1697. SkipWhitespace ();
  1698. int quoteChar = ReadChar ();
  1699. char [] expect1_0 = new char [3];
  1700. int versionLength = 0;
  1701. switch (quoteChar) {
  1702. case '\'':
  1703. case '"':
  1704. while (PeekChar () != quoteChar) {
  1705. if (PeekChar () == -1)
  1706. throw new XmlException (this as IXmlLineInfo,
  1707. "Invalid version declaration inside text declaration.");
  1708. else if (versionLength == 3)
  1709. throw new XmlException (this as IXmlLineInfo,
  1710. "Invalid version number inside text declaration.");
  1711. else {
  1712. expect1_0 [versionLength] = (char) ReadChar ();
  1713. versionLength++;
  1714. if (versionLength == 3 && new String (expect1_0) != "1.0")
  1715. throw new XmlException (this as IXmlLineInfo,
  1716. "Invalid version number inside text declaration.");
  1717. }
  1718. }
  1719. ReadChar ();
  1720. SkipWhitespace ();
  1721. break;
  1722. default:
  1723. throw new XmlException (this as IXmlLineInfo,
  1724. "Invalid version declaration inside text declaration.");
  1725. }
  1726. }
  1727. if (PeekChar () == 'e') {
  1728. Expect ("encoding");
  1729. ExpectAfterWhitespace ('=');
  1730. SkipWhitespace ();
  1731. int quoteChar = ReadChar ();
  1732. switch (quoteChar) {
  1733. case '\'':
  1734. case '"':
  1735. while (PeekChar () != quoteChar)
  1736. if (ReadChar () == -1)
  1737. throw new XmlException (this as IXmlLineInfo,
  1738. "Invalid encoding declaration inside text declaration.");
  1739. ReadChar ();
  1740. SkipWhitespace ();
  1741. break;
  1742. default:
  1743. throw new XmlException (this as IXmlLineInfo,
  1744. "Invalid encoding declaration inside text declaration.");
  1745. }
  1746. // Encoding value should be checked inside XmlInputStream.
  1747. }
  1748. else
  1749. throw new XmlException (this as IXmlLineInfo,
  1750. "Encoding declaration is mandatory in text declaration.");
  1751. Expect ("?>");
  1752. }
  1753. // The reader is positioned on the first character after
  1754. // the leading '<!'.
  1755. private void ReadDeclaration ()
  1756. {
  1757. int ch = PeekChar ();
  1758. switch (ch)
  1759. {
  1760. case '-':
  1761. Expect ("--");
  1762. ReadComment ();
  1763. break;
  1764. case '[':
  1765. ReadChar ();
  1766. Expect ("CDATA[");
  1767. ReadCDATA ();
  1768. break;
  1769. case 'D':
  1770. Expect ("DOCTYPE");
  1771. ReadDoctypeDecl ();
  1772. break;
  1773. default:
  1774. throw new XmlException (this as IXmlLineInfo,
  1775. "Unexpected declaration markup was found.");
  1776. }
  1777. }
  1778. // The reader is positioned on the first character after
  1779. // the leading '<!--'.
  1780. private void ReadComment ()
  1781. {
  1782. if (currentState == XmlNodeType.None)
  1783. currentState = XmlNodeType.XmlDeclaration;
  1784. ClearValueBuffer ();
  1785. while (PeekChar () != -1) {
  1786. int ch = ReadChar ();
  1787. if (ch == '-' && PeekChar () == '-') {
  1788. ReadChar ();
  1789. if (PeekChar () != '>')
  1790. throw new XmlException (this as IXmlLineInfo,"comments cannot contain '--'");
  1791. ReadChar ();
  1792. break;
  1793. }
  1794. if (XmlChar.IsInvalid (ch))
  1795. throw new XmlException (this as IXmlLineInfo,
  1796. "Not allowed character was found.");
  1797. AppendValueChar (ch);
  1798. }
  1799. SetProperties (
  1800. XmlNodeType.Comment, // nodeType
  1801. String.Empty, // name
  1802. false, // isEmptyElement
  1803. null, // value: create only when required
  1804. true // clearAttributes
  1805. );
  1806. }
  1807. // The reader is positioned on the first character after
  1808. // the leading '<![CDATA['.
  1809. private void ReadCDATA ()
  1810. {
  1811. if (currentState != XmlNodeType.Element)
  1812. throw new XmlException (this as IXmlLineInfo,
  1813. "CDATA section cannot appear in this state.");
  1814. ClearValueBuffer ();
  1815. bool skip = false;
  1816. int ch = 0;
  1817. while (PeekChar () != -1) {
  1818. if (!skip)
  1819. ch = ReadChar ();
  1820. skip = false;
  1821. if (ch == ']' && PeekChar () == ']') {
  1822. ch = ReadChar (); // ']'
  1823. if (PeekChar () == '>') {
  1824. ReadChar (); // '>'
  1825. break;
  1826. } else {
  1827. skip = true;
  1828. }
  1829. }
  1830. if (normalization && XmlChar.IsInvalid (ch))
  1831. throw new XmlException (this, "Invalid character was found.");
  1832. AppendValueChar (ch);
  1833. }
  1834. SetProperties (
  1835. XmlNodeType.CDATA, // nodeType
  1836. String.Empty, // name
  1837. false, // isEmptyElement
  1838. null, // value: create only when required
  1839. true // clearAttributes
  1840. );
  1841. }
  1842. // The reader is positioned on the first character after
  1843. // the leading '<!DOCTYPE'.
  1844. private void ReadDoctypeDecl ()
  1845. {
  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. }