XmlTextReader.cs 67 KB

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