2
0

XmlTextReader.cs 73 KB

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