XmlTextReader.cs 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716
  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 && normalization; }
  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 = new string (Reader.valueBuffer, 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 ();
  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 char [] valueBuffer;
  714. private int valueLength;
  715. private int valueCapacity;
  716. private const int initialValueCapacity = 256;
  717. private char [] currentTagBuffer;
  718. private int currentTagLength;
  719. private int currentTagCapacity;
  720. private const int initialCurrentTagCapacity = 256;
  721. private TextReader reader;
  722. private char [] peekChars;
  723. private int peekCharsIndex;
  724. private int peekCharsLength;
  725. private const int peekCharCapacity = 1024;
  726. private int line;
  727. private int column;
  728. private int currentLinkedNodeLineNumber;
  729. private int currentLinkedNodeLinePosition;
  730. private bool useProceedingLineInfo;
  731. private XmlNodeType startNodeType;
  732. // State machine attribute.
  733. // XmlDeclaration: after the first node.
  734. // DocumentType: after doctypedecl
  735. // Element: inside document element
  736. // EndElement: after document element
  737. private XmlNodeType currentState;
  738. // For ReadChars()/ReadBase64()/ReadBinHex()
  739. private bool shouldSkipUntilEndTag;
  740. XmlReaderBinarySupport.CharGetter binaryCharGetter;
  741. // These values are never re-initialized.
  742. private bool namespaces = true;
  743. private WhitespaceHandling whitespaceHandling = WhitespaceHandling.All;
  744. private XmlResolver resolver = new XmlUrlResolver ();
  745. private bool normalization = false;
  746. private bool checkCharacters;
  747. private bool prohibitDtd = false;
  748. private bool closeInput = true;
  749. private EntityHandling entityHandling; // 2.0
  750. private XmlException NotWFError (string message)
  751. {
  752. return new XmlException (this as IXmlLineInfo, BaseURI, message);
  753. }
  754. private void Init ()
  755. {
  756. currentToken = new XmlTokenInfo (this);
  757. cursorToken = currentToken;
  758. currentAttribute = -1;
  759. currentAttributeValue = -1;
  760. attributeCount = 0;
  761. readState = ReadState.Initial;
  762. allowMultipleRoot = false;
  763. depth = 0;
  764. elementDepth = 0;
  765. depthUp = false;
  766. popScope = allowMultipleRoot = false;
  767. elementNames = new string [10];
  768. elementNameStackPos = 0;
  769. isStandalone = false;
  770. returnEntityReference = false;
  771. entityReferenceName = String.Empty;
  772. nameBuffer = new char [initialNameCapacity];
  773. nameLength = 0;
  774. nameCapacity = initialNameCapacity;
  775. valueBuffer = new char [initialValueCapacity];
  776. valueLength = 0;
  777. valueCapacity = initialValueCapacity;
  778. currentTagBuffer = new char [initialCurrentTagCapacity];
  779. currentTagLength = 0;
  780. currentTagCapacity = initialCurrentTagCapacity;
  781. peekCharsIndex = 0;
  782. peekCharsLength = 0;
  783. if (peekChars == null)
  784. peekChars = new char [peekCharCapacity];
  785. line = 1;
  786. column = 1;
  787. currentLinkedNodeLineNumber = currentLinkedNodeLinePosition = 0;
  788. useProceedingLineInfo = false;
  789. currentState = XmlNodeType.None;
  790. shouldSkipUntilEndTag = false;
  791. binaryCharGetter = new XmlReaderBinarySupport.CharGetter (ReadChars);
  792. checkCharacters = true;
  793. #if NET_2_0
  794. if (Settings != null)
  795. checkCharacters = Settings.CheckCharacters;
  796. #endif
  797. prohibitDtd = false;
  798. closeInput = true;
  799. entityHandling = EntityHandling.ExpandCharEntities;
  800. }
  801. private void InitializeContext (string url, XmlParserContext context, TextReader fragment, XmlNodeType fragType)
  802. {
  803. startNodeType = fragType;
  804. parserContext = context;
  805. if (context == null) {
  806. XmlNameTable nt = new NameTable ();
  807. parserContext = new XmlParserContext (nt,
  808. new XmlNamespaceManager (nt),
  809. String.Empty,
  810. XmlSpace.None);
  811. }
  812. if (url != null && url.Length > 0) {
  813. Uri uri = null;
  814. try {
  815. uri = new Uri (url);
  816. } catch (Exception) {
  817. string path = Path.GetFullPath ("./a");
  818. uri = new Uri (new Uri (path), url);
  819. }
  820. parserContext.BaseURI = uri.ToString ();
  821. }
  822. Init ();
  823. reader = fragment;
  824. switch (fragType) {
  825. case XmlNodeType.Attribute:
  826. reader = new StringReader (fragment.ReadToEnd ().Replace ("\"", "&quot;"));
  827. SkipTextDeclaration ();
  828. break;
  829. case XmlNodeType.Element:
  830. currentState = XmlNodeType.Element;
  831. allowMultipleRoot = true;
  832. SkipTextDeclaration ();
  833. break;
  834. case XmlNodeType.Document:
  835. break;
  836. default:
  837. throw new XmlException (String.Format ("NodeType {0} is not allowed to create XmlTextReader.", fragType));
  838. }
  839. }
  840. #if NET_2_0
  841. [MonoTODO ("Test")]
  842. internal ConformanceLevel Conformance {
  843. set {
  844. if (value == ConformanceLevel.Fragment) {
  845. currentState = XmlNodeType.Element;
  846. allowMultipleRoot = true;
  847. }
  848. }
  849. }
  850. internal void AdjustLineInfoOffset (int lineNumberOffset, int linePositionOffset)
  851. {
  852. line += lineNumberOffset;
  853. column += linePositionOffset;
  854. }
  855. internal void SetNameTable (XmlNameTable nameTable)
  856. {
  857. parserContext.NameTable = nameTable;
  858. }
  859. #endif
  860. // Use this method rather than setting the properties
  861. // directly so that all the necessary properties can
  862. // be changed in harmony with each other. Maybe the
  863. // fields should be in a seperate class to help enforce
  864. // this.
  865. //
  866. // Namespace URI could not be provided here.
  867. private void SetProperties (
  868. XmlNodeType nodeType,
  869. string name,
  870. string prefix,
  871. string localName,
  872. bool isEmptyElement,
  873. string value,
  874. bool clearAttributes)
  875. {
  876. SetTokenProperties (currentToken, nodeType, name, prefix, localName, isEmptyElement, value, clearAttributes);
  877. currentToken.LineNumber = this.currentLinkedNodeLineNumber;
  878. currentToken.LinePosition = this.currentLinkedNodeLinePosition;
  879. }
  880. private void SetTokenProperties (
  881. XmlTokenInfo token,
  882. XmlNodeType nodeType,
  883. string name,
  884. string prefix,
  885. string localName,
  886. bool isEmptyElement,
  887. string value,
  888. bool clearAttributes)
  889. {
  890. token.NodeType = nodeType;
  891. token.Name = name;
  892. token.Prefix = prefix;
  893. token.LocalName = localName;
  894. token.IsEmptyElement = isEmptyElement;
  895. token.Value = value;
  896. this.elementDepth = depth;
  897. if (clearAttributes)
  898. ClearAttributes ();
  899. }
  900. private void ClearAttributes ()
  901. {
  902. for (int i = 0; i < attributeCount; i++)
  903. attributeTokens [i].Clear ();
  904. attributeCount = 0;
  905. currentAttribute = -1;
  906. currentAttributeValue = -1;
  907. }
  908. private int PeekChar ()
  909. {
  910. if (peekCharsLength == peekCharsIndex) {
  911. if (!ReadTextReader ())
  912. return -1;
  913. else
  914. return PeekChar ();
  915. }
  916. return peekChars [peekCharsIndex];
  917. }
  918. private int ReadChar ()
  919. {
  920. int ch;
  921. if (peekCharsLength == peekCharsIndex) {
  922. if (!ReadTextReader ())
  923. return -1;
  924. }
  925. ch = peekChars [peekCharsIndex++];
  926. if (ch == '\n') {
  927. line++;
  928. column = 1;
  929. } else if (ch == 0) {
  930. return -1;
  931. } else {
  932. column++;
  933. }
  934. if (currentState != XmlNodeType.Element)
  935. AppendCurrentTagChar (ch);
  936. return ch;
  937. }
  938. private bool ReadTextReader ()
  939. {
  940. peekCharsIndex = 0;
  941. peekCharsLength = reader.Read (peekChars, 0, peekCharCapacity);
  942. return (peekCharsLength != 0);
  943. }
  944. private string ExpandSurrogateChar (int ch)
  945. {
  946. if (ch < Char.MaxValue)
  947. return ((char) ch).ToString ();
  948. else {
  949. char [] tmp = new char [] {(char) (ch / 0x10000 + 0xD800 - 1), (char) (ch % 0x10000 + 0xDC00)};
  950. return new string (tmp);
  951. }
  952. }
  953. private bool ReadContent ()
  954. {
  955. currentTagLength = 0;
  956. if (popScope) {
  957. parserContext.NamespaceManager.PopScope ();
  958. parserContext.PopScope ();
  959. popScope = false;
  960. }
  961. if (returnEntityReference)
  962. SetEntityReferenceProperties ();
  963. else {
  964. int c = PeekChar ();
  965. if (c == -1) {
  966. readState = ReadState.EndOfFile;
  967. ClearValueBuffer ();
  968. SetProperties (
  969. XmlNodeType.None, // nodeType
  970. String.Empty, // name
  971. String.Empty, // prefix
  972. String.Empty, // localName
  973. false, // isEmptyElement
  974. null, // value
  975. true // clearAttributes
  976. );
  977. if (depth > 0)
  978. throw NotWFError ("unexpected end of file. Current depth is " + depth);
  979. return false;
  980. } else {
  981. switch (c) {
  982. case '<':
  983. ReadChar ();
  984. switch (PeekChar ())
  985. {
  986. case '/':
  987. ReadChar ();
  988. ReadEndTag ();
  989. break;
  990. case '?':
  991. ReadChar ();
  992. ReadProcessingInstruction ();
  993. break;
  994. case '!':
  995. ReadChar ();
  996. ReadDeclaration ();
  997. break;
  998. default:
  999. ReadStartTag ();
  1000. break;
  1001. }
  1002. break;
  1003. case '\r':
  1004. case '\n':
  1005. case '\t':
  1006. case ' ':
  1007. if (whitespaceHandling == WhitespaceHandling.All ||
  1008. whitespaceHandling == WhitespaceHandling.Significant)
  1009. ReadWhitespace ();
  1010. else {
  1011. SkipWhitespace ();
  1012. return ReadContent ();
  1013. }
  1014. break;
  1015. default:
  1016. ReadText (true);
  1017. break;
  1018. }
  1019. }
  1020. }
  1021. return this.ReadState != ReadState.EndOfFile;
  1022. }
  1023. private void SetEntityReferenceProperties ()
  1024. {
  1025. DTDEntityDeclaration decl = DTD != null ? DTD.EntityDecls [entityReferenceName] : null;
  1026. if (this.isStandalone)
  1027. if (DTD == null || decl == null || !decl.IsInternalSubset)
  1028. throw NotWFError ("Standalone document must not contain any references to an non-internally declared entity.");
  1029. if (decl != null && decl.NotationName != null)
  1030. throw NotWFError ("Reference to any unparsed entities is not allowed here.");
  1031. ClearValueBuffer ();
  1032. SetProperties (
  1033. XmlNodeType.EntityReference, // nodeType
  1034. entityReferenceName, // name
  1035. String.Empty, // prefix
  1036. entityReferenceName, // localName
  1037. false, // isEmptyElement
  1038. null, // value
  1039. true // clearAttributes
  1040. );
  1041. returnEntityReference = false;
  1042. entityReferenceName = String.Empty;
  1043. }
  1044. // The leading '<' has already been consumed.
  1045. private void ReadStartTag ()
  1046. {
  1047. if (currentState == XmlNodeType.EndElement)
  1048. throw NotWFError ("Multiple document element was detected.");
  1049. currentState = XmlNodeType.Element;
  1050. parserContext.NamespaceManager.PushScope ();
  1051. currentLinkedNodeLineNumber = line;
  1052. currentLinkedNodeLinePosition = column;
  1053. string prefix, localName;
  1054. string name = ReadName (out prefix, out localName);
  1055. if (currentState == XmlNodeType.EndElement)
  1056. throw NotWFError ("document has terminated, cannot open new element");
  1057. bool isEmptyElement = false;
  1058. ClearAttributes ();
  1059. SkipWhitespace ();
  1060. if (XmlChar.IsFirstNameChar (PeekChar ()))
  1061. ReadAttributes (false);
  1062. cursorToken = this.currentToken;
  1063. // fill namespaces
  1064. for (int i = 0; i < attributeCount; i++)
  1065. attributeTokens [i].FillXmlns ();
  1066. for (int i = 0; i < attributeCount; i++)
  1067. attributeTokens [i].FillNamespace ();
  1068. // quick name check
  1069. for (int i = 0; i < attributeCount; i++) {
  1070. for (int j = i + 1; j < attributeCount; j++)
  1071. if (Object.ReferenceEquals (attributeTokens [i].Name, attributeTokens [j].Name) ||
  1072. (Object.ReferenceEquals (attributeTokens [i].LocalName, attributeTokens [j].LocalName) &&
  1073. Object.ReferenceEquals (attributeTokens [i].NamespaceURI, attributeTokens [j].NamespaceURI)))
  1074. throw NotWFError ("Attribute name and qualified name must be identical.");
  1075. }
  1076. if (PeekChar () == '/') {
  1077. ReadChar ();
  1078. isEmptyElement = true;
  1079. popScope = true;
  1080. }
  1081. else {
  1082. depthUp = true;
  1083. PushElementName (name);
  1084. }
  1085. parserContext.PushScope ();
  1086. Expect ('>');
  1087. SetProperties (
  1088. XmlNodeType.Element, // nodeType
  1089. name, // name
  1090. prefix, // prefix
  1091. localName, // name
  1092. isEmptyElement, // isEmptyElement
  1093. null, // value
  1094. false // clearAttributes
  1095. );
  1096. if (prefix.Length > 0)
  1097. currentToken.NamespaceURI = LookupNamespace (prefix, true);
  1098. else if (namespaces)
  1099. currentToken.NamespaceURI = parserContext.NamespaceManager.DefaultNamespace;
  1100. if (namespaces) {
  1101. if (NamespaceURI == null)
  1102. throw NotWFError (String.Format ("'{0}' is undeclared namespace.", Prefix));
  1103. try {
  1104. for (int i = 0; i < attributeCount; i++) {
  1105. MoveToAttribute (i);
  1106. if (NamespaceURI == null)
  1107. throw NotWFError (String.Format ("'{0}' is undeclared namespace.", Prefix));
  1108. }
  1109. } finally {
  1110. MoveToElement ();
  1111. }
  1112. }
  1113. for (int i = 0; i < attributeCount; i++) {
  1114. if (!Object.ReferenceEquals (attributeTokens [i].Prefix, XmlNamespaceManager.PrefixXml))
  1115. continue;
  1116. string aname = attributeTokens [i].LocalName;
  1117. string value = attributeTokens [i].Value;
  1118. switch (aname) {
  1119. case "base":
  1120. if (this.resolver != null) {
  1121. Uri buri =
  1122. BaseURI != String.Empty ?
  1123. new Uri (BaseURI) : null;
  1124. Uri uri = resolver.ResolveUri (
  1125. buri, value);
  1126. parserContext.BaseURI =
  1127. uri != null ?
  1128. uri.ToString () :
  1129. String.Empty;
  1130. }
  1131. else
  1132. parserContext.BaseURI = value;
  1133. break;
  1134. case "lang":
  1135. parserContext.XmlLang = value;
  1136. break;
  1137. case "space":
  1138. switch (value) {
  1139. case "preserve":
  1140. parserContext.XmlSpace = XmlSpace.Preserve;
  1141. break;
  1142. case "default":
  1143. parserContext.XmlSpace = XmlSpace.Default;
  1144. break;
  1145. default:
  1146. throw NotWFError (String.Format ("Invalid xml:space value: {0}", value));
  1147. }
  1148. break;
  1149. }
  1150. }
  1151. if (IsEmptyElement)
  1152. CheckCurrentStateUpdate ();
  1153. }
  1154. private void PushElementName (string name)
  1155. {
  1156. if (elementNames.Length == elementNameStackPos) {
  1157. string [] newArray = new string [elementNames.Length * 2];
  1158. Array.Copy (elementNames, 0, newArray, 0, elementNameStackPos);
  1159. elementNames = newArray;
  1160. }
  1161. elementNames [elementNameStackPos++] = name;
  1162. }
  1163. // The reader is positioned on the first character
  1164. // of the element's name.
  1165. private void ReadEndTag ()
  1166. {
  1167. if (currentState != XmlNodeType.Element)
  1168. throw NotWFError ("End tag cannot appear in this state.");
  1169. currentLinkedNodeLineNumber = line;
  1170. currentLinkedNodeLinePosition = column;
  1171. string prefix, localName;
  1172. string name = ReadName (out prefix, out localName);
  1173. if (elementNameStackPos == 0)
  1174. throw NotWFError ("closing element without matching opening element");
  1175. string expected = elementNames [--elementNameStackPos];
  1176. if (expected != name)
  1177. throw NotWFError (String.Format ("unmatched closing element: expected {0} but found {1}", expected, name));
  1178. ExpectAfterWhitespace ('>');
  1179. --depth;
  1180. SetProperties (
  1181. XmlNodeType.EndElement, // nodeType
  1182. name, // name
  1183. prefix, // prefix
  1184. localName, // localName
  1185. false, // isEmptyElement
  1186. null, // value
  1187. true // clearAttributes
  1188. );
  1189. if (prefix.Length > 0)
  1190. currentToken.NamespaceURI = LookupNamespace (prefix, true);
  1191. else if (namespaces)
  1192. currentToken.NamespaceURI = parserContext.NamespaceManager.DefaultNamespace;
  1193. popScope = true;
  1194. CheckCurrentStateUpdate ();
  1195. }
  1196. private void CheckCurrentStateUpdate ()
  1197. {
  1198. if (depth == 0 && !allowMultipleRoot && (IsEmptyElement || NodeType == XmlNodeType.EndElement))
  1199. currentState = XmlNodeType.EndElement;
  1200. }
  1201. private void AppendSurrogatePairNameChar (int ch)
  1202. {
  1203. nameBuffer [nameLength++] = (char) (ch / 0x10000 + 0xD800 - 1);
  1204. if (nameLength == nameCapacity)
  1205. ExpandNameCapacity ();
  1206. nameBuffer [nameLength++] = (char) (ch % 0x10000 + 0xDC00);
  1207. }
  1208. private void ExpandNameCapacity ()
  1209. {
  1210. nameCapacity = nameCapacity * 2;
  1211. char [] oldNameBuffer = nameBuffer;
  1212. nameBuffer = new char [nameCapacity];
  1213. Array.Copy (oldNameBuffer, nameBuffer, nameLength);
  1214. }
  1215. private void AppendValueChar (int ch)
  1216. {
  1217. if (valueLength == valueCapacity)
  1218. ExpandValueCapacity ();
  1219. if (ch < Char.MaxValue)
  1220. valueBuffer [valueLength++] = (char) ch;
  1221. else
  1222. AppendSurrogatePairValueChar (ch);
  1223. }
  1224. private void AppendSurrogatePairValueChar (int ch)
  1225. {
  1226. valueBuffer [valueLength++] = (char) (ch / 0x10000 + 0xD800 - 1);
  1227. if (valueLength == valueCapacity)
  1228. ExpandValueCapacity ();
  1229. valueBuffer [valueLength++] = (char) (ch % 0x10000 + 0xDC00);
  1230. }
  1231. private void ExpandValueCapacity ()
  1232. {
  1233. valueCapacity = valueCapacity * 2;
  1234. char [] oldValueBuffer = valueBuffer;
  1235. valueBuffer = new char [valueCapacity];
  1236. Array.Copy (oldValueBuffer, valueBuffer, valueLength);
  1237. }
  1238. private string CreateValueString ()
  1239. {
  1240. return new string (valueBuffer, 0, valueLength);
  1241. }
  1242. private void ClearValueBuffer ()
  1243. {
  1244. valueLength = 0;
  1245. }
  1246. private void AppendCurrentTagChar (int ch)
  1247. {
  1248. if (currentTagLength == currentTagCapacity)
  1249. ExpandCurrentTagCapacity ();
  1250. if (ch < Char.MaxValue)
  1251. currentTagBuffer [currentTagLength++] = (char) ch;
  1252. else {
  1253. currentTagBuffer [currentTagLength++] = (char) (ch / 0x10000 + 0xD800 - 1);
  1254. if (currentTagLength == currentTagCapacity)
  1255. ExpandCurrentTagCapacity ();
  1256. currentTagBuffer [currentTagLength++] = (char) (ch % 0x10000 + 0xDC00);
  1257. }
  1258. }
  1259. private void ExpandCurrentTagCapacity ()
  1260. {
  1261. currentTagCapacity = currentTagCapacity * 2;
  1262. char [] oldCurrentTagBuffer = currentTagBuffer;
  1263. currentTagBuffer = new char [currentTagCapacity];
  1264. Array.Copy (oldCurrentTagBuffer, currentTagBuffer, currentTagLength);
  1265. }
  1266. // The reader is positioned on the first character
  1267. // of the text.
  1268. private void ReadText (bool notWhitespace)
  1269. {
  1270. if (currentState != XmlNodeType.Element)
  1271. throw NotWFError ("Text node cannot appear in this state.");
  1272. if (notWhitespace)
  1273. ClearValueBuffer ();
  1274. int ch = PeekChar ();
  1275. bool previousWasCloseBracket = false;
  1276. while (ch != '<' && ch != -1) {
  1277. if (ch == '&') {
  1278. ReadChar ();
  1279. ch = ReadReference (false);
  1280. if (returnEntityReference) // Returns -1 if char validation should not be done
  1281. break;
  1282. } else if (normalization && ch == '\r') {
  1283. ReadChar ();
  1284. ch = ReadChar ();
  1285. if (ch != '\n')
  1286. // append '\n' instead of '\r'.
  1287. AppendValueChar ('\n');
  1288. // and in case of "\r\n", discard '\r'.
  1289. } else {
  1290. if (CharacterChecking && XmlChar.IsInvalid (ch))
  1291. throw NotWFError ("Not allowed character was found.");
  1292. ch = ReadChar ();
  1293. }
  1294. // FIXME: it might be optimized by the JIT later,
  1295. // AppendValueChar (ch);
  1296. {
  1297. if (valueLength == valueCapacity)
  1298. ExpandValueCapacity ();
  1299. if (ch < Char.MaxValue)
  1300. valueBuffer [valueLength++] = (char) ch;
  1301. else
  1302. AppendSurrogatePairValueChar (ch);
  1303. }
  1304. // Block "]]>"
  1305. if (ch == ']') {
  1306. if (previousWasCloseBracket)
  1307. if (PeekChar () == '>')
  1308. throw NotWFError ("Inside text content, character sequence ']]>' is not allowed.");
  1309. previousWasCloseBracket = true;
  1310. }
  1311. else if (previousWasCloseBracket)
  1312. previousWasCloseBracket = false;
  1313. ch = PeekChar ();
  1314. notWhitespace = true;
  1315. }
  1316. if (returnEntityReference && valueLength == 0) {
  1317. SetEntityReferenceProperties ();
  1318. } else {
  1319. XmlNodeType nodeType = notWhitespace ? XmlNodeType.Text :
  1320. this.XmlSpace == XmlSpace.Preserve ? XmlNodeType.SignificantWhitespace : XmlNodeType.Whitespace;
  1321. SetProperties (
  1322. nodeType, // nodeType
  1323. String.Empty, // name
  1324. String.Empty, // prefix
  1325. String.Empty, // localName
  1326. false, // isEmptyElement
  1327. null, // value: create only when required
  1328. true // clearAttributes
  1329. );
  1330. }
  1331. }
  1332. // The leading '&' has already been consumed.
  1333. // Returns true if the entity reference isn't a simple
  1334. // character reference or one of the predefined entities.
  1335. // This allows the ReadText method to break so that the
  1336. // next call to Read will return the EntityReference node.
  1337. private int ReadReference (bool ignoreEntityReferences)
  1338. {
  1339. if (PeekChar () == '#') {
  1340. ReadChar ();
  1341. return ReadCharacterReference ();
  1342. } else
  1343. return ReadEntityReference (ignoreEntityReferences);
  1344. }
  1345. private int ReadCharacterReference ()
  1346. {
  1347. int value = 0;
  1348. if (PeekChar () == 'x') {
  1349. ReadChar ();
  1350. while (PeekChar () != ';' && PeekChar () != -1) {
  1351. int ch = ReadChar ();
  1352. if (ch >= '0' && ch <= '9')
  1353. value = (value << 4) + ch - '0';
  1354. else if (ch >= 'A' && ch <= 'F')
  1355. value = (value << 4) + ch - 'A' + 10;
  1356. else if (ch >= 'a' && ch <= 'f')
  1357. value = (value << 4) + ch - 'a' + 10;
  1358. else
  1359. throw NotWFError (String.Format (CultureInfo.InvariantCulture,
  1360. "invalid hexadecimal digit: {0} (#x{1:X})",
  1361. (char) ch,
  1362. ch));
  1363. }
  1364. } else {
  1365. while (PeekChar () != ';' && PeekChar () != -1) {
  1366. int ch = ReadChar ();
  1367. if (ch >= '0' && ch <= '9')
  1368. value = value * 10 + ch - '0';
  1369. else
  1370. throw NotWFError (String.Format (CultureInfo.InvariantCulture,
  1371. "invalid decimal digit: {0} (#x{1:X})",
  1372. (char) ch,
  1373. ch));
  1374. }
  1375. }
  1376. ReadChar (); // ';'
  1377. // There is no way to save surrogate pairs...
  1378. if (CharacterChecking && XmlChar.IsInvalid (value))
  1379. throw NotWFError ("Referenced character was not allowed in XML. Normalization is " + normalization + ", checkCharacters = " + checkCharacters);
  1380. return value;
  1381. }
  1382. // Returns -1 if it should not be validated.
  1383. // Real EOF must not be detected here.
  1384. private int ReadEntityReference (bool ignoreEntityReferences)
  1385. {
  1386. string name = ReadName ();
  1387. Expect (';');
  1388. int predefined = XmlChar.GetPredefinedEntity (name);
  1389. if (predefined >= 0)
  1390. return predefined;
  1391. else {
  1392. if (ignoreEntityReferences) {
  1393. AppendValueChar ('&');
  1394. for (int i = 0; i < name.Length; i++)
  1395. AppendValueChar (name [i]);
  1396. AppendValueChar (';');
  1397. } else {
  1398. returnEntityReference = true;
  1399. entityReferenceName = name;
  1400. }
  1401. }
  1402. return -1;
  1403. }
  1404. // The reader is positioned on the first character of
  1405. // the attribute name.
  1406. private void ReadAttributes (bool isXmlDecl)
  1407. {
  1408. int peekChar = -1;
  1409. bool requireWhitespace = false;
  1410. currentAttribute = -1;
  1411. currentAttributeValue = -1;
  1412. do {
  1413. if (!SkipWhitespace () && requireWhitespace)
  1414. throw NotWFError ("Unexpected token. Name is required here.");
  1415. IncrementAttributeToken ();
  1416. currentAttributeToken.LineNumber = line;
  1417. currentAttributeToken.LinePosition = column;
  1418. string prefix, localName;
  1419. currentAttributeToken.Name = ReadName (out prefix, out localName);
  1420. currentAttributeToken.Prefix = prefix;
  1421. currentAttributeToken.LocalName = localName;
  1422. ExpectAfterWhitespace ('=');
  1423. SkipWhitespace ();
  1424. ReadAttributeValueTokens (-1);
  1425. // This hack is required for xmldecl which has
  1426. // both effective attributes and Value.
  1427. string dummyValue;
  1428. if (isXmlDecl)
  1429. dummyValue = currentAttributeToken.Value;
  1430. attributeCount++;
  1431. if (!SkipWhitespace ())
  1432. requireWhitespace = true;
  1433. peekChar = PeekChar ();
  1434. if (isXmlDecl) {
  1435. if (peekChar == '?')
  1436. break;
  1437. }
  1438. else if (peekChar == '/' || peekChar == '>')
  1439. break;
  1440. } while (peekChar != -1);
  1441. currentAttribute = -1;
  1442. currentAttributeValue = -1;
  1443. }
  1444. private void AddDtdAttribute (string name, string value)
  1445. {
  1446. IncrementAttributeToken ();
  1447. XmlAttributeTokenInfo ati = attributeTokens [currentAttribute];
  1448. ati.Name = parserContext.NameTable.Add (name);
  1449. ati.Prefix = String.Empty;
  1450. ati.NamespaceURI = String.Empty;
  1451. IncrementAttributeValueToken ();
  1452. XmlTokenInfo vti = attributeValueTokens [currentAttributeValue];
  1453. vti.Value = value;
  1454. SetTokenProperties (vti,
  1455. XmlNodeType.Text,
  1456. String.Empty,
  1457. String.Empty,
  1458. String.Empty,
  1459. false,
  1460. value,
  1461. false);
  1462. attributeCount++;
  1463. }
  1464. private void IncrementAttributeToken ()
  1465. {
  1466. currentAttribute++;
  1467. if (attributeTokens.Length == currentAttribute) {
  1468. XmlAttributeTokenInfo [] newArray =
  1469. new XmlAttributeTokenInfo [attributeTokens.Length * 2];
  1470. attributeTokens.CopyTo (newArray, 0);
  1471. attributeTokens = newArray;
  1472. }
  1473. if (attributeTokens [currentAttribute] == null)
  1474. attributeTokens [currentAttribute] = new XmlAttributeTokenInfo (this);
  1475. currentAttributeToken = attributeTokens [currentAttribute];
  1476. currentAttributeToken.Clear ();
  1477. }
  1478. private void IncrementAttributeValueToken ()
  1479. {
  1480. currentAttributeValue++;
  1481. if (attributeValueTokens.Length == currentAttributeValue) {
  1482. XmlTokenInfo [] newArray = new XmlTokenInfo [attributeValueTokens.Length * 2];
  1483. attributeValueTokens.CopyTo (newArray, 0);
  1484. attributeValueTokens = newArray;
  1485. }
  1486. if (attributeValueTokens [currentAttributeValue] == null)
  1487. attributeValueTokens [currentAttributeValue] = new XmlTokenInfo (this);
  1488. currentAttributeValueToken = attributeValueTokens [currentAttributeValue];
  1489. currentAttributeValueToken.Clear ();
  1490. }
  1491. // LAMESPEC: Orthodox XML reader should normalize attribute values
  1492. private void ReadAttributeValueTokens (int dummyQuoteChar)
  1493. {
  1494. int quoteChar = (dummyQuoteChar < 0) ? ReadChar () : dummyQuoteChar;
  1495. if (quoteChar != '\'' && quoteChar != '\"')
  1496. throw NotWFError ("an attribute value was not quoted");
  1497. currentAttributeToken.QuoteChar = (char) quoteChar;
  1498. IncrementAttributeValueToken ();
  1499. currentAttributeToken.ValueTokenStartIndex = currentAttributeValue;
  1500. currentAttributeValueToken.LineNumber = line;
  1501. currentAttributeValueToken.LinePosition = column;
  1502. bool incrementToken = false;
  1503. bool isNewToken = true;
  1504. bool loop = true;
  1505. int ch = 0;
  1506. currentAttributeValueToken.ValueBufferStart = valueLength;
  1507. while (loop) {
  1508. ch = ReadChar ();
  1509. if (ch == quoteChar)
  1510. break;
  1511. if (incrementToken) {
  1512. IncrementAttributeValueToken ();
  1513. currentAttributeValueToken.ValueBufferStart = valueLength;
  1514. currentAttributeValueToken.LineNumber = line;
  1515. currentAttributeValueToken.LinePosition = column;
  1516. incrementToken = false;
  1517. isNewToken = true;
  1518. }
  1519. switch (ch)
  1520. {
  1521. case '<':
  1522. throw NotWFError ("attribute values cannot contain '<'");
  1523. case -1:
  1524. if (dummyQuoteChar < 0)
  1525. throw NotWFError ("unexpected end of file in an attribute value");
  1526. else // Attribute value constructor.
  1527. loop = false;
  1528. break;
  1529. case '\r':
  1530. if (!normalization)
  1531. goto default;
  1532. if (PeekChar () == '\n')
  1533. continue; // skip '\r'.
  1534. //
  1535. // The csc in MS.NET 2.0 beta 1 barfs on this goto, so work around that
  1536. //
  1537. //goto case '\n';
  1538. if (!normalization)
  1539. goto default;
  1540. ch = ' ';
  1541. goto default;
  1542. case '\n':
  1543. case '\t':
  1544. // When Normalize = true, then replace
  1545. // all spaces to ' '
  1546. if (!normalization)
  1547. goto default;
  1548. ch = ' ';
  1549. goto default;
  1550. case '&':
  1551. if (PeekChar () == '#') {
  1552. ReadChar ();
  1553. ch = ReadCharacterReference ();
  1554. if (CharacterChecking && XmlChar.IsInvalid (ch))
  1555. throw NotWFError ("Not allowed character was found.");
  1556. AppendValueChar (ch);
  1557. break;
  1558. }
  1559. // Check XML 1.0 section 3.1 WFC.
  1560. string entName = ReadName ();
  1561. Expect (';');
  1562. int predefined = XmlChar.GetPredefinedEntity (entName);
  1563. if (predefined < 0) {
  1564. CheckAttributeEntityReferenceWFC (entName);
  1565. #if NET_2_0
  1566. if (entityHandling == EntityHandling.ExpandEntities) {
  1567. string value = DTD.GenerateEntityAttributeText (entName);
  1568. foreach (char c in value)
  1569. AppendValueChar (c);
  1570. } else
  1571. #endif
  1572. {
  1573. currentAttributeValueToken.ValueBufferEnd = valueLength;
  1574. currentAttributeValueToken.NodeType = XmlNodeType.Text;
  1575. if (!isNewToken)
  1576. IncrementAttributeValueToken ();
  1577. currentAttributeValueToken.Name = entName;
  1578. currentAttributeValueToken.Value = String.Empty;
  1579. currentAttributeValueToken.NodeType = XmlNodeType.EntityReference;
  1580. incrementToken = true;
  1581. }
  1582. }
  1583. else
  1584. AppendValueChar (predefined);
  1585. break;
  1586. default:
  1587. if (CharacterChecking && XmlChar.IsInvalid (ch))
  1588. throw NotWFError ("Invalid character was found.");
  1589. // FIXME: it might be optimized by the JIT later,
  1590. // AppendValueChar (ch);
  1591. {
  1592. if (valueLength == valueCapacity)
  1593. ExpandValueCapacity ();
  1594. if (ch < Char.MaxValue)
  1595. valueBuffer [valueLength++] = (char) ch;
  1596. else
  1597. AppendSurrogatePairValueChar (ch);
  1598. }
  1599. break;
  1600. }
  1601. isNewToken = false;
  1602. }
  1603. if (!incrementToken) {
  1604. currentAttributeValueToken.ValueBufferEnd = valueLength;
  1605. currentAttributeValueToken.NodeType = XmlNodeType.Text;
  1606. }
  1607. currentAttributeToken.ValueTokenEndIndex = currentAttributeValue;
  1608. }
  1609. private void CheckAttributeEntityReferenceWFC (string entName)
  1610. {
  1611. DTDEntityDeclaration entDecl =
  1612. DTD == null ? null : DTD.EntityDecls [entName];
  1613. if (entDecl == null) {
  1614. if (entityHandling == EntityHandling.ExpandEntities
  1615. || (DTD != null && resolver != null && entDecl == null))
  1616. throw NotWFError (String.Format ("Referenced entity '{0}' does not exist.", entName));
  1617. else
  1618. return;
  1619. }
  1620. if (entDecl.HasExternalReference)
  1621. throw NotWFError ("Reference to external entities is not allowed in the value of an attribute.");
  1622. if (isStandalone && !entDecl.IsInternalSubset)
  1623. throw NotWFError ("Reference to external entities is not allowed in the internal subset.");
  1624. if (entDecl.EntityValue.IndexOf ('<') >= 0)
  1625. throw NotWFError ("Attribute must not contain character '<' either directly or indirectly by way of entity references.");
  1626. }
  1627. // The reader is positioned on the first character
  1628. // of the target.
  1629. //
  1630. // It may be xml declaration or processing instruction.
  1631. private void ReadProcessingInstruction ()
  1632. {
  1633. string target = ReadName ();
  1634. if (target == "xml") {
  1635. ReadXmlDeclaration ();
  1636. return;
  1637. } else if (target.ToLower (CultureInfo.InvariantCulture) == "xml")
  1638. throw NotWFError ("Not allowed processing instruction name which starts with 'X', 'M', 'L' was found.");
  1639. if (currentState == XmlNodeType.None)
  1640. currentState = XmlNodeType.XmlDeclaration;
  1641. if (!SkipWhitespace ())
  1642. if (PeekChar () != '?')
  1643. throw NotWFError ("Invalid processing instruction name was found.");
  1644. ClearValueBuffer ();
  1645. while (PeekChar () != -1) {
  1646. int ch = ReadChar ();
  1647. if (ch == '?' && PeekChar () == '>') {
  1648. ReadChar ();
  1649. break;
  1650. }
  1651. if (CharacterChecking && XmlChar.IsInvalid (ch))
  1652. throw NotWFError ("Invalid character was found.");
  1653. AppendValueChar (ch);
  1654. }
  1655. SetProperties (
  1656. XmlNodeType.ProcessingInstruction, // nodeType
  1657. target, // name
  1658. String.Empty, // prefix
  1659. target, // localName
  1660. false, // isEmptyElement
  1661. null, // value: create only when required
  1662. true // clearAttributes
  1663. );
  1664. }
  1665. // The reader is positioned after "<?xml "
  1666. private void ReadXmlDeclaration ()
  1667. {
  1668. if (currentState != XmlNodeType.None) {
  1669. throw NotWFError ("XML declaration cannot appear in this state.");
  1670. }
  1671. currentState = XmlNodeType.XmlDeclaration;
  1672. ClearAttributes ();
  1673. ReadAttributes (true); // They must have "version."
  1674. string version = GetAttribute ("version");
  1675. string message = null;
  1676. if (attributeTokens [0].Name != "version" || version != "1.0")
  1677. message = "Version 1.0 declaration is required in XML Declaration.";
  1678. else if (attributeCount > 1 &&
  1679. (attributeTokens [1].Name != "encoding" &&
  1680. attributeTokens [1].Name != "standalone"))
  1681. message = "Invalid Xml Declaration markup was found.";
  1682. else if (attributeCount > 2 && attributeTokens [2].Name != "standalone")
  1683. message = "Invalid Xml Declaration markup was found.";
  1684. string sa = GetAttribute ("standalone");
  1685. if (sa != null && sa != "yes" && sa != "no")
  1686. message = String.Format ("Only 'yes' or 'no' is allowed for standalone. Value was '{0}'", sa);
  1687. this.isStandalone = (sa == "yes");
  1688. if (message != null)
  1689. throw NotWFError (message);
  1690. SetProperties (
  1691. XmlNodeType.XmlDeclaration, // nodeType
  1692. "xml", // name
  1693. String.Empty, // prefix
  1694. "xml", // localName
  1695. false, // isEmptyElement
  1696. new string (currentTagBuffer, 6, currentTagLength - 6), // value
  1697. false // clearAttributes
  1698. );
  1699. Expect ("?>");
  1700. }
  1701. private void SkipTextDeclaration ()
  1702. {
  1703. this.currentState = XmlNodeType.Element;
  1704. if (PeekChar () != '<')
  1705. return;
  1706. ReadChar ();
  1707. if (PeekChar () != '?') {
  1708. peekCharsIndex = 0;
  1709. return;
  1710. }
  1711. ReadChar ();
  1712. while (peekCharsIndex < 6) {
  1713. if (PeekChar () < 0)
  1714. break;
  1715. else
  1716. ReadChar ();
  1717. }
  1718. if (new string (peekChars, 2, 4) != "xml ") {
  1719. if (new string (peekChars, 2, 3).ToLower (CultureInfo.InvariantCulture) == "xml") {
  1720. throw NotWFError ("Processing instruction name must not be character sequence 'X' 'M' 'L' with case insensitivity.");
  1721. }
  1722. peekCharsIndex = 0;
  1723. return;
  1724. }
  1725. SkipWhitespace ();
  1726. // version decl
  1727. if (PeekChar () == 'v') {
  1728. Expect ("version");
  1729. ExpectAfterWhitespace ('=');
  1730. SkipWhitespace ();
  1731. int quoteChar = ReadChar ();
  1732. char [] expect1_0 = new char [3];
  1733. int versionLength = 0;
  1734. switch (quoteChar) {
  1735. case '\'':
  1736. case '"':
  1737. while (PeekChar () != quoteChar) {
  1738. if (PeekChar () == -1)
  1739. throw NotWFError ("Invalid version declaration inside text declaration.");
  1740. else if (versionLength == 3)
  1741. throw NotWFError ("Invalid version number inside text declaration.");
  1742. else {
  1743. expect1_0 [versionLength] = (char) ReadChar ();
  1744. versionLength++;
  1745. if (versionLength == 3 && new String (expect1_0) != "1.0")
  1746. throw NotWFError ("Invalid version number inside text declaration.");
  1747. }
  1748. }
  1749. ReadChar ();
  1750. SkipWhitespace ();
  1751. break;
  1752. default:
  1753. throw NotWFError ("Invalid version declaration inside text declaration.");
  1754. }
  1755. }
  1756. if (PeekChar () == 'e') {
  1757. Expect ("encoding");
  1758. ExpectAfterWhitespace ('=');
  1759. SkipWhitespace ();
  1760. int quoteChar = ReadChar ();
  1761. switch (quoteChar) {
  1762. case '\'':
  1763. case '"':
  1764. while (PeekChar () != quoteChar)
  1765. if (ReadChar () == -1)
  1766. throw NotWFError ("Invalid encoding declaration inside text declaration.");
  1767. ReadChar ();
  1768. SkipWhitespace ();
  1769. break;
  1770. default:
  1771. throw NotWFError ("Invalid encoding declaration inside text declaration.");
  1772. }
  1773. // Encoding value should be checked inside XmlInputStream.
  1774. }
  1775. else
  1776. throw NotWFError ("Encoding declaration is mandatory in text declaration.");
  1777. Expect ("?>");
  1778. }
  1779. // The reader is positioned on the first character after
  1780. // the leading '<!'.
  1781. private void ReadDeclaration ()
  1782. {
  1783. int ch = PeekChar ();
  1784. switch (ch)
  1785. {
  1786. case '-':
  1787. Expect ("--");
  1788. ReadComment ();
  1789. break;
  1790. case '[':
  1791. ReadChar ();
  1792. Expect ("CDATA[");
  1793. ReadCDATA ();
  1794. break;
  1795. case 'D':
  1796. Expect ("DOCTYPE");
  1797. ReadDoctypeDecl ();
  1798. break;
  1799. default:
  1800. throw NotWFError ("Unexpected declaration markup was found.");
  1801. }
  1802. }
  1803. // The reader is positioned on the first character after
  1804. // the leading '<!--'.
  1805. private void ReadComment ()
  1806. {
  1807. if (currentState == XmlNodeType.None)
  1808. currentState = XmlNodeType.XmlDeclaration;
  1809. ClearValueBuffer ();
  1810. while (PeekChar () != -1) {
  1811. int ch = ReadChar ();
  1812. if (ch == '-' && PeekChar () == '-') {
  1813. ReadChar ();
  1814. if (PeekChar () != '>')
  1815. throw NotWFError ("comments cannot contain '--'");
  1816. ReadChar ();
  1817. break;
  1818. }
  1819. if (XmlChar.IsInvalid (ch))
  1820. throw NotWFError ("Not allowed character was found.");
  1821. AppendValueChar (ch);
  1822. }
  1823. SetProperties (
  1824. XmlNodeType.Comment, // nodeType
  1825. String.Empty, // name
  1826. String.Empty, // prefix
  1827. String.Empty, // localName
  1828. false, // isEmptyElement
  1829. null, // value: create only when required
  1830. true // clearAttributes
  1831. );
  1832. }
  1833. // The reader is positioned on the first character after
  1834. // the leading '<![CDATA['.
  1835. private void ReadCDATA ()
  1836. {
  1837. if (currentState != XmlNodeType.Element)
  1838. throw NotWFError ("CDATA section cannot appear in this state.");
  1839. ClearValueBuffer ();
  1840. bool skip = false;
  1841. int ch = 0;
  1842. while (PeekChar () != -1) {
  1843. if (!skip)
  1844. ch = ReadChar ();
  1845. skip = false;
  1846. if (ch == ']' && PeekChar () == ']') {
  1847. ch = ReadChar (); // ']'
  1848. if (PeekChar () == '>') {
  1849. ReadChar (); // '>'
  1850. break;
  1851. } else {
  1852. skip = true;
  1853. }
  1854. }
  1855. if (normalization && ch == '\r') {
  1856. ch = PeekChar ();
  1857. if (ch != '\n')
  1858. // append '\n' instead of '\r'.
  1859. AppendValueChar ('\n');
  1860. // otherwise, discard '\r'.
  1861. continue;
  1862. }
  1863. if (CharacterChecking && XmlChar.IsInvalid (ch))
  1864. throw NotWFError ("Invalid character was found.");
  1865. // FIXME: it might be optimized by the JIT later,
  1866. // AppendValueChar (ch);
  1867. {
  1868. if (valueLength == valueCapacity)
  1869. ExpandValueCapacity ();
  1870. if (ch < Char.MaxValue)
  1871. valueBuffer [valueLength++] = (char) ch;
  1872. else
  1873. AppendSurrogatePairValueChar (ch);
  1874. }
  1875. }
  1876. SetProperties (
  1877. XmlNodeType.CDATA, // nodeType
  1878. String.Empty, // name
  1879. String.Empty, // prefix
  1880. String.Empty, // localName
  1881. false, // isEmptyElement
  1882. null, // value: create only when required
  1883. true // clearAttributes
  1884. );
  1885. }
  1886. // The reader is positioned on the first character after
  1887. // the leading '<!DOCTYPE'.
  1888. private void ReadDoctypeDecl ()
  1889. {
  1890. if (prohibitDtd)
  1891. throw NotWFError ("Document Type Declaration (DTD) is prohibited in this XML.");
  1892. switch (currentState) {
  1893. case XmlNodeType.DocumentType:
  1894. case XmlNodeType.Element:
  1895. case XmlNodeType.EndElement:
  1896. throw NotWFError ("Document type cannot appear in this state.");
  1897. }
  1898. currentState = XmlNodeType.DocumentType;
  1899. string doctypeName = null;
  1900. string publicId = null;
  1901. string systemId = null;
  1902. int intSubsetStartLine = 0;
  1903. int intSubsetStartColumn = 0;
  1904. SkipWhitespace ();
  1905. doctypeName = ReadName ();
  1906. SkipWhitespace ();
  1907. switch(PeekChar ())
  1908. {
  1909. case 'S':
  1910. systemId = ReadSystemLiteral (true);
  1911. break;
  1912. case 'P':
  1913. publicId = ReadPubidLiteral ();
  1914. if (!SkipWhitespace ())
  1915. throw NotWFError ("Whitespace is required between PUBLIC id and SYSTEM id.");
  1916. systemId = ReadSystemLiteral (false);
  1917. break;
  1918. }
  1919. SkipWhitespace ();
  1920. if(PeekChar () == '[')
  1921. {
  1922. // read markupdecl etc. or end of decl
  1923. ReadChar ();
  1924. intSubsetStartLine = this.LineNumber;
  1925. intSubsetStartColumn = this.LinePosition;
  1926. int startPos = currentTagLength;
  1927. ReadInternalSubset ();
  1928. int endPos = currentTagLength - 1;
  1929. parserContext.InternalSubset = new string (currentTagBuffer, startPos, endPos - startPos);
  1930. }
  1931. // end of DOCTYPE decl.
  1932. ExpectAfterWhitespace ('>');
  1933. GenerateDTDObjectModel (doctypeName, publicId,
  1934. systemId, parserContext.InternalSubset,
  1935. intSubsetStartLine, intSubsetStartColumn);
  1936. // set properties for <!DOCTYPE> node
  1937. SetProperties (
  1938. XmlNodeType.DocumentType, // nodeType
  1939. doctypeName, // name
  1940. String.Empty, // prefix
  1941. doctypeName, // localName
  1942. false, // isEmptyElement
  1943. parserContext.InternalSubset, // value
  1944. true // clearAttributes
  1945. );
  1946. if (publicId != null)
  1947. AddDtdAttribute ("PUBLIC", publicId);
  1948. if (systemId != null)
  1949. AddDtdAttribute ("SYSTEM", systemId);
  1950. currentAttribute = currentAttributeValue = -1;
  1951. }
  1952. internal DTDObjectModel GenerateDTDObjectModel (string name, string publicId,
  1953. string systemId, string internalSubset)
  1954. {
  1955. return GenerateDTDObjectModel (name, publicId, systemId, internalSubset, 0, 0);
  1956. }
  1957. internal DTDObjectModel GenerateDTDObjectModel (string name, string publicId,
  1958. string systemId, string internalSubset, int intSubsetStartLine, int intSubsetStartColumn)
  1959. {
  1960. // now compile DTD
  1961. parserContext.Dtd = new DTDObjectModel (this.NameTable); // merges both internal and external subsets in the meantime,
  1962. DTD.BaseURI = BaseURI;
  1963. DTD.Name = name;
  1964. DTD.PublicId = publicId;
  1965. DTD.SystemId = systemId;
  1966. DTD.InternalSubset = internalSubset;
  1967. DTD.XmlResolver = resolver;
  1968. DTD.IsStandalone = isStandalone;
  1969. DTD.LineNumber = line;
  1970. DTD.LinePosition = column;
  1971. DTDReader dr = new DTDReader (DTD, intSubsetStartLine, intSubsetStartColumn);
  1972. dr.Normalization = this.normalization;
  1973. return dr.GenerateDTDObjectModel ();
  1974. }
  1975. private enum DtdInputState
  1976. {
  1977. Free = 1,
  1978. ElementDecl,
  1979. AttlistDecl,
  1980. EntityDecl,
  1981. NotationDecl,
  1982. PI,
  1983. Comment,
  1984. InsideSingleQuoted,
  1985. InsideDoubleQuoted,
  1986. }
  1987. private class DtdInputStateStack
  1988. {
  1989. Stack intern = new Stack ();
  1990. public DtdInputStateStack ()
  1991. {
  1992. Push (DtdInputState.Free);
  1993. }
  1994. public DtdInputState Peek ()
  1995. {
  1996. return (DtdInputState) intern.Peek ();
  1997. }
  1998. public DtdInputState Pop ()
  1999. {
  2000. return (DtdInputState) intern.Pop ();
  2001. }
  2002. public void Push (DtdInputState val)
  2003. {
  2004. intern.Push (val);
  2005. }
  2006. }
  2007. DtdInputStateStack stateStack = new DtdInputStateStack ();
  2008. DtdInputState State {
  2009. get { return stateStack.Peek (); }
  2010. }
  2011. // Simply read but not generate any result.
  2012. private void ReadInternalSubset ()
  2013. {
  2014. bool continueParse = true;
  2015. while (continueParse) {
  2016. switch (ReadChar ()) {
  2017. case ']':
  2018. switch (State) {
  2019. case DtdInputState.Free:
  2020. continueParse = false;
  2021. break;
  2022. case DtdInputState.InsideDoubleQuoted:
  2023. continue;
  2024. case DtdInputState.InsideSingleQuoted:
  2025. continue;
  2026. default:
  2027. throw NotWFError ("unexpected end of file at DTD.");
  2028. }
  2029. break;
  2030. case -1:
  2031. throw NotWFError ("unexpected end of file at DTD.");
  2032. case '<':
  2033. switch (State) {
  2034. case DtdInputState.InsideDoubleQuoted:
  2035. case DtdInputState.InsideSingleQuoted:
  2036. case DtdInputState.Comment:
  2037. continue; // well-formed
  2038. }
  2039. int c = ReadChar ();
  2040. switch (c) {
  2041. case '?':
  2042. stateStack.Push (DtdInputState.PI);
  2043. break;
  2044. case '!':
  2045. switch (ReadChar ()) {
  2046. case 'E':
  2047. switch (ReadChar ()) {
  2048. case 'L':
  2049. Expect ("EMENT");
  2050. stateStack.Push (DtdInputState.ElementDecl);
  2051. break;
  2052. case 'N':
  2053. Expect ("TITY");
  2054. stateStack.Push (DtdInputState.EntityDecl);
  2055. break;
  2056. default:
  2057. throw NotWFError ("unexpected token '<!E'.");
  2058. }
  2059. break;
  2060. case 'A':
  2061. Expect ("TTLIST");
  2062. stateStack.Push (DtdInputState.AttlistDecl);
  2063. break;
  2064. case 'N':
  2065. Expect ("OTATION");
  2066. stateStack.Push (DtdInputState.NotationDecl);
  2067. break;
  2068. case '-':
  2069. Expect ('-');
  2070. stateStack.Push (DtdInputState.Comment);
  2071. break;
  2072. }
  2073. break;
  2074. default:
  2075. throw NotWFError (String.Format ("unexpected '<{0}'.", (char) c));
  2076. }
  2077. break;
  2078. case '\'':
  2079. if (State == DtdInputState.InsideSingleQuoted)
  2080. stateStack.Pop ();
  2081. else if (State != DtdInputState.InsideDoubleQuoted && State != DtdInputState.Comment)
  2082. stateStack.Push (DtdInputState.InsideSingleQuoted);
  2083. break;
  2084. case '"':
  2085. if (State == DtdInputState.InsideDoubleQuoted)
  2086. stateStack.Pop ();
  2087. else if (State != DtdInputState.InsideSingleQuoted && State != DtdInputState.Comment)
  2088. stateStack.Push (DtdInputState.InsideDoubleQuoted);
  2089. break;
  2090. case '>':
  2091. switch (State) {
  2092. case DtdInputState.ElementDecl:
  2093. goto case DtdInputState.NotationDecl;
  2094. case DtdInputState.AttlistDecl:
  2095. goto case DtdInputState.NotationDecl;
  2096. case DtdInputState.EntityDecl:
  2097. goto case DtdInputState.NotationDecl;
  2098. case DtdInputState.NotationDecl:
  2099. stateStack.Pop ();
  2100. break;
  2101. case DtdInputState.InsideDoubleQuoted:
  2102. case DtdInputState.InsideSingleQuoted:
  2103. case DtdInputState.Comment:
  2104. continue;
  2105. default:
  2106. throw NotWFError ("unexpected token '>'");
  2107. }
  2108. break;
  2109. case '?':
  2110. if (State == DtdInputState.PI) {
  2111. if (ReadChar () == '>')
  2112. stateStack.Pop ();
  2113. }
  2114. break;
  2115. case '-':
  2116. if (State == DtdInputState.Comment) {
  2117. if (PeekChar () == '-') {
  2118. ReadChar ();
  2119. Expect ('>');
  2120. stateStack.Pop ();
  2121. }
  2122. }
  2123. break;
  2124. case '%':
  2125. if (State != DtdInputState.Free && State != DtdInputState.EntityDecl && State != DtdInputState.Comment && State != DtdInputState.InsideDoubleQuoted && State != DtdInputState.InsideSingleQuoted)
  2126. throw NotWFError ("Parameter Entity Reference cannot appear as a part of markupdecl (see XML spec 2.8).");
  2127. break;
  2128. }
  2129. }
  2130. }
  2131. // The reader is positioned on the first 'S' of "SYSTEM".
  2132. private string ReadSystemLiteral (bool expectSYSTEM)
  2133. {
  2134. if(expectSYSTEM) {
  2135. Expect ("SYSTEM");
  2136. if (!SkipWhitespace ())
  2137. throw NotWFError ("Whitespace is required after 'SYSTEM'.");
  2138. }
  2139. else
  2140. SkipWhitespace ();
  2141. int quoteChar = ReadChar (); // apos or quot
  2142. int c = 0;
  2143. ClearValueBuffer ();
  2144. while (c != quoteChar) {
  2145. c = ReadChar ();
  2146. if (c < 0)
  2147. throw NotWFError ("Unexpected end of stream in ExternalID.");
  2148. if (c != quoteChar)
  2149. AppendValueChar (c);
  2150. }
  2151. return CreateValueString ();
  2152. }
  2153. private string ReadPubidLiteral()
  2154. {
  2155. Expect ("PUBLIC");
  2156. if (!SkipWhitespace ())
  2157. throw NotWFError ("Whitespace is required after 'PUBLIC'.");
  2158. int quoteChar = ReadChar ();
  2159. int c = 0;
  2160. ClearValueBuffer ();
  2161. while(c != quoteChar)
  2162. {
  2163. c = ReadChar ();
  2164. if(c < 0) throw NotWFError ("Unexpected end of stream in ExternalID.");
  2165. if(c != quoteChar && !XmlChar.IsPubidChar (c))
  2166. throw NotWFError (String.Format ("character '{0}' not allowed for PUBLIC ID", (char)c ));
  2167. if (c != quoteChar)
  2168. AppendValueChar (c);
  2169. }
  2170. return CreateValueString ();
  2171. }
  2172. // The reader is positioned on the first character
  2173. // of the name.
  2174. private string ReadName ()
  2175. {
  2176. string prefix, local;
  2177. return ReadName (out prefix, out local);
  2178. }
  2179. private string ReadName (out string prefix, out string localName)
  2180. {
  2181. // FIXME: need to reject non-QName names?
  2182. int ch = PeekChar ();
  2183. if (!XmlChar.IsFirstNameChar (ch))
  2184. throw NotWFError (String.Format (CultureInfo.InvariantCulture, "a name did not start with a legal character {0} ({1})", ch, (char) ch));
  2185. nameLength = 0;
  2186. ch = ReadChar ();
  2187. // AppendNameChar (ch);
  2188. {
  2189. if (nameLength == nameCapacity)
  2190. ExpandNameCapacity ();
  2191. if (ch < Char.MaxValue)
  2192. nameBuffer [nameLength++] = (char) ch;
  2193. else
  2194. AppendSurrogatePairNameChar (ch);
  2195. }
  2196. int colonAt = -1;
  2197. while (XmlChar.IsNameChar (PeekChar ())) {
  2198. ch = ReadChar ();
  2199. if (namespaces && colonAt < 0 && ch == ':')
  2200. colonAt = nameLength;
  2201. // AppendNameChar (ch);
  2202. {
  2203. if (nameLength == nameCapacity)
  2204. ExpandNameCapacity ();
  2205. if (ch < Char.MaxValue)
  2206. nameBuffer [nameLength++] = (char) ch;
  2207. else
  2208. AppendSurrogatePairNameChar (ch);
  2209. }
  2210. }
  2211. string name = parserContext.NameTable.Add (nameBuffer, 0, nameLength);
  2212. if (namespaces && colonAt > 0) {
  2213. prefix = parserContext.NameTable.Add (nameBuffer, 0, colonAt);
  2214. localName = parserContext.NameTable.Add (nameBuffer, colonAt + 1, nameLength - colonAt - 1);
  2215. }
  2216. else {
  2217. prefix = String.Empty;
  2218. localName = name;
  2219. }
  2220. return name;
  2221. }
  2222. // Read the next character and compare it against the
  2223. // specified character.
  2224. private void Expect (int expected)
  2225. {
  2226. int ch = ReadChar ();
  2227. if (ch != expected) {
  2228. throw NotWFError (String.Format (CultureInfo.InvariantCulture,
  2229. "expected '{0}' ({1:X}) but found '{2}' ({3:X})",
  2230. (char) expected,
  2231. expected,
  2232. (char) ch,
  2233. ch));
  2234. }
  2235. }
  2236. private void Expect (string expected)
  2237. {
  2238. int len = expected.Length;
  2239. for(int i=0; i< len; i++)
  2240. Expect (expected[i]);
  2241. }
  2242. private void ExpectAfterWhitespace (char c)
  2243. {
  2244. while (true) {
  2245. int i = ReadChar ();
  2246. if (i < 0x21 && XmlChar.IsWhitespace (i))
  2247. continue;
  2248. if (c != i)
  2249. throw NotWFError (String.Format (CultureInfo.InvariantCulture, "Expected {0}, but found {1} [{2}]", c, (char) i, i));
  2250. break;
  2251. }
  2252. }
  2253. // Does not consume the first non-whitespace character.
  2254. private bool SkipWhitespace ()
  2255. {
  2256. // FIXME: It should be inlined by the JIT.
  2257. // bool skipped = XmlChar.IsWhitespace (PeekChar ());
  2258. int ch = PeekChar ();
  2259. bool skipped = (ch == 0x20 || ch == 0x9 || ch == 0xA || ch == 0xD);
  2260. if (!skipped)
  2261. return false;
  2262. ReadChar ();
  2263. // FIXME: It should be inlined by the JIT.
  2264. // while (XmlChar.IsWhitespace (PeekChar ()))
  2265. // ReadChar ();
  2266. while ((ch = PeekChar ()) == 0x20 || ch == 0x9 || ch == 0xA || ch == 0xD)
  2267. ReadChar ();
  2268. return skipped;
  2269. }
  2270. private void ReadWhitespace ()
  2271. {
  2272. if (currentState == XmlNodeType.None)
  2273. currentState = XmlNodeType.XmlDeclaration;
  2274. ClearValueBuffer ();
  2275. int ch = PeekChar ();
  2276. do {
  2277. // FIXME: it might be optimized by the JIT later,
  2278. // AppendValueChar (ReadChar ());
  2279. {
  2280. ch = ReadChar ();
  2281. if (valueLength == valueCapacity)
  2282. ExpandValueCapacity ();
  2283. if (ch < Char.MaxValue)
  2284. valueBuffer [valueLength++] = (char) ch;
  2285. else
  2286. AppendSurrogatePairValueChar (ch);
  2287. }
  2288. // FIXME: It should be inlined by the JIT.
  2289. // } while ((ch = PeekChar ()) != -1 && XmlChar.IsWhitespace (ch));
  2290. ch = PeekChar ();
  2291. } while (ch == 0x20 || ch == 0x9 || ch == 0xA || ch == 0xD);
  2292. if (currentState == XmlNodeType.Element && ch != -1 && ch != '<')
  2293. ReadText (false);
  2294. else {
  2295. XmlNodeType nodeType = (this.XmlSpace == XmlSpace.Preserve) ?
  2296. XmlNodeType.SignificantWhitespace : XmlNodeType.Whitespace;
  2297. SetProperties (nodeType,
  2298. String.Empty,
  2299. String.Empty,
  2300. String.Empty,
  2301. false,
  2302. null, // value: create only when required
  2303. true);
  2304. }
  2305. return;
  2306. }
  2307. // Returns -1 if it should throw an error.
  2308. private int ReadCharsInternal (char [] buffer, int offset, int length)
  2309. {
  2310. shouldSkipUntilEndTag = true;
  2311. int bufIndex = offset;
  2312. for (int i = 0; i < length; i++) {
  2313. int c = PeekChar ();
  2314. switch (c) {
  2315. case -1:
  2316. throw NotWFError ("Unexpected end of xml.");
  2317. case '<':
  2318. ReadChar ();
  2319. if (PeekChar () != '/') {
  2320. buffer [bufIndex++] = '<';
  2321. continue;
  2322. }
  2323. // Seems to skip immediate EndElement
  2324. Expect ('/');
  2325. if (depthUp) {
  2326. depth++;
  2327. depthUp = false;
  2328. }
  2329. ReadEndTag ();
  2330. shouldSkipUntilEndTag = false;
  2331. Read (); // move to the next node
  2332. return i;
  2333. default:
  2334. ReadChar ();
  2335. if (c < Char.MaxValue)
  2336. buffer [bufIndex++] = (char) c;
  2337. else {
  2338. buffer [bufIndex++] = (char) (c / 0x10000 + 0xD800 - 1);
  2339. buffer [bufIndex++] = (char) (c % 0x10000 + 0xDC00);
  2340. }
  2341. break;
  2342. }
  2343. }
  2344. return length;
  2345. }
  2346. private bool ReadUntilEndTag ()
  2347. {
  2348. if (Depth == 0)
  2349. currentState = XmlNodeType.EndElement;
  2350. int ch;
  2351. do {
  2352. ch = ReadChar ();
  2353. switch (ch) {
  2354. case -1:
  2355. throw NotWFError ("Unexpected end of xml.");
  2356. case '<':
  2357. if (PeekChar () != '/')
  2358. continue;
  2359. ReadChar ();
  2360. string name = ReadName ();
  2361. if (name != elementNames [elementNameStackPos - 1])
  2362. continue;
  2363. Expect ('>');
  2364. depth--;
  2365. elementNames [--elementNameStackPos] = null;
  2366. return Read ();
  2367. }
  2368. } while (true);
  2369. }
  2370. #endregion
  2371. }
  2372. }