XmlTextReader.cs 70 KB

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