XmlTextReader.cs 69 KB

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