XmlTextReader.cs 76 KB

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