2
0

XmlTextReader.cs 74 KB

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