2
0

XmlTextReader.cs 67 KB

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