XmlTextReader.cs 65 KB

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