XmlTextReader.cs 73 KB

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