XmlTextReader.cs 69 KB

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