XmlTextReader.cs 68 KB

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