XmlTextReader.cs 66 KB

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