XmlTextReader.cs 75 KB

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