XmlTextReader.cs 67 KB

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