XmlTextReader.cs 64 KB

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