XmlTextReader.cs 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781
  1. //
  2. // System.Xml.XmlTextReader
  3. //
  4. // Author:
  5. // Jason Diamond ([email protected])
  6. // Adam Treat ([email protected])
  7. //
  8. // (C) 2001, 2002 Jason Diamond http://injektilo.org/
  9. //
  10. // FIXME:
  11. // This can only parse basic XML: elements, attributes, processing
  12. // instructions, and comments are OK.
  13. //
  14. // It barfs on DOCTYPE declarations.
  15. // => No barfing, but parsing is incomplete.
  16. // DTD nodes are not still created.
  17. //
  18. // There's also no checking being done for validity.
  19. //
  20. // More checking should be done for well-formedness.
  21. //
  22. // NameTables aren't being used everywhere yet.
  23. //
  24. // Some thought needs to be given to performance. There's too many
  25. // strings being allocated.
  26. //
  27. // Some of the MoveTo methods haven't been implemented yet.
  28. //
  29. // xml:space, xml:lang, and xml:base aren't being tracked.
  30. //
  31. using System;
  32. using System.Collections;
  33. using System.IO;
  34. using System.Text;
  35. namespace System.Xml
  36. {
  37. public class XmlTextReader : XmlReader, IXmlLineInfo
  38. {
  39. WhitespaceHandling whitespaceHandling = WhitespaceHandling.All;
  40. #region Constructors
  41. protected XmlTextReader ()
  42. {
  43. }
  44. public XmlTextReader (Stream input)
  45. : this (new StreamReader (input))
  46. {
  47. }
  48. public XmlTextReader (string url)
  49. : this(url, new NameTable ())
  50. {
  51. }
  52. public XmlTextReader (TextReader input)
  53. : this (input, new NameTable ())
  54. {
  55. }
  56. protected XmlTextReader (XmlNameTable nt)
  57. : this (String.Empty, null, XmlNodeType.None, null)
  58. {
  59. }
  60. public XmlTextReader (Stream input, XmlNameTable nt)
  61. : this(new StreamReader (input), nt)
  62. {
  63. }
  64. public XmlTextReader (string url, Stream input)
  65. : this (url, new StreamReader (input))
  66. {
  67. }
  68. public XmlTextReader (string url, TextReader input)
  69. : this (url, input, new NameTable ())
  70. {
  71. }
  72. [MonoTODO("Non-filename-url must be supported. Waiting for WebClient")]
  73. public XmlTextReader (string url, XmlNameTable nt)
  74. // : this(url, new StreamReader ((Stream)new XmlUrlResolver ().GetEntity (new Uri (url), null, typeof(Stream))), nt)
  75. : this (url, new StreamReader (url), nt)
  76. {
  77. }
  78. public XmlTextReader (TextReader input, XmlNameTable nt)
  79. : this(String.Empty, input, nt)
  80. {
  81. }
  82. public XmlTextReader (Stream xmlFragment, XmlNodeType fragType, XmlParserContext context)
  83. : this (String.Empty, new StreamReader (xmlFragment), fragType, context)
  84. {
  85. }
  86. public XmlTextReader (string url, Stream input, XmlNameTable nt)
  87. : this (url, new StreamReader (input), nt)
  88. {
  89. }
  90. public XmlTextReader (string url, TextReader input, XmlNameTable nt)
  91. : this (url, input, XmlNodeType.Document, new XmlParserContext (nt, new XmlNamespaceManager (nt), null, XmlSpace.None))
  92. {
  93. }
  94. [MonoTODO("TODO as same as private XmlTextReader(TextReader, XmlNodeType, XmlParserContext)")]
  95. public XmlTextReader (string xmlFragment, XmlNodeType fragType, XmlParserContext context)
  96. : this (String.Empty, new StringReader (xmlFragment), fragType, context)
  97. {
  98. }
  99. // TODO still remains as described at head of this file,
  100. // but it might not be TODO of the constructors...
  101. XmlTextReader (string url, TextReader fragment, XmlNodeType fragType, XmlParserContext context)
  102. {
  103. this.SetReaderContext(url, context);
  104. this.SetReaderFragment(fragment, fragType);
  105. }
  106. #endregion
  107. #region Properties
  108. public override int AttributeCount
  109. {
  110. get { return attributes.Count; }
  111. }
  112. public override string BaseURI
  113. {
  114. get { return parserContext.BaseURI; }
  115. }
  116. public override int Depth
  117. {
  118. get {
  119. return elementDepth;
  120. }
  121. }
  122. public Encoding Encoding
  123. {
  124. get { return parserContext.Encoding; }
  125. }
  126. public override bool EOF
  127. {
  128. get
  129. {
  130. return
  131. readState == ReadState.EndOfFile ||
  132. readState == ReadState.Closed;
  133. }
  134. }
  135. public override bool HasValue
  136. {
  137. get { return value != String.Empty; }
  138. }
  139. public override bool IsDefault
  140. {
  141. get
  142. {
  143. // XmlTextReader does not expand default attributes.
  144. return false;
  145. }
  146. }
  147. public override bool IsEmptyElement
  148. {
  149. get { return isEmptyElement; }
  150. }
  151. public override string this [int i]
  152. {
  153. get { return GetAttribute (i); }
  154. }
  155. public override string this [string name]
  156. {
  157. get { return GetAttribute (name); }
  158. }
  159. public override string this [string localName, string namespaceName]
  160. {
  161. get { return GetAttribute (localName, namespaceName); }
  162. }
  163. public int LineNumber
  164. {
  165. get { return line; }
  166. }
  167. public int LinePosition
  168. {
  169. get { return column; }
  170. }
  171. public override string LocalName
  172. {
  173. get { return localName; }
  174. }
  175. public override string Name
  176. {
  177. get { return name; }
  178. }
  179. [MonoTODO]
  180. public bool Namespaces
  181. {
  182. get { throw new NotImplementedException (); }
  183. set { throw new NotImplementedException (); }
  184. }
  185. public override string NamespaceURI
  186. {
  187. get { return namespaceURI; }
  188. }
  189. public override XmlNameTable NameTable
  190. {
  191. get { return parserContext.NameTable; }
  192. }
  193. public override XmlNodeType NodeType
  194. {
  195. get { return nodeType; }
  196. }
  197. [MonoTODO]
  198. public bool Normalization
  199. {
  200. get { throw new NotImplementedException (); }
  201. set { throw new NotImplementedException (); }
  202. }
  203. public override string Prefix
  204. {
  205. get { return prefix; }
  206. }
  207. public override char QuoteChar
  208. {
  209. get {
  210. // value string holds attribute quotation char.
  211. if (NodeType == XmlNodeType.Attribute)
  212. return value [0];
  213. else
  214. return '"';
  215. }
  216. }
  217. public override ReadState ReadState
  218. {
  219. get { return readState; }
  220. }
  221. public override string Value
  222. {
  223. get {
  224. if(NodeType == XmlNodeType.Attribute)
  225. return UnescapeAttributeValue(value);
  226. else
  227. return value;
  228. }
  229. }
  230. public WhitespaceHandling WhitespaceHandling
  231. {
  232. get { return whitespaceHandling; }
  233. set { whitespaceHandling = value; }
  234. }
  235. [MonoTODO]
  236. public override string XmlLang
  237. {
  238. get { throw new NotImplementedException (); }
  239. }
  240. [MonoTODO]
  241. public XmlResolver XmlResolver
  242. {
  243. set { throw new NotImplementedException (); }
  244. }
  245. [MonoTODO]
  246. public override XmlSpace XmlSpace
  247. {
  248. get { throw new NotImplementedException (); }
  249. }
  250. #endregion
  251. #region Methods
  252. [MonoTODO]
  253. public override void Close ()
  254. {
  255. readState = ReadState.Closed;
  256. }
  257. public override string GetAttribute (int i)
  258. {
  259. if (i > attributes.Count)
  260. throw new ArgumentOutOfRangeException ("i is smaller than AttributeCount");
  261. else
  262. return UnescapeAttributeValue (attributes [orderedAttributes [i]] as string);
  263. }
  264. public override string GetAttribute (string name)
  265. {
  266. return attributes.ContainsKey (name) ?
  267. UnescapeAttributeValue (attributes [name] as string) : String.Empty;
  268. }
  269. public override string GetAttribute (string localName, string namespaceURI)
  270. {
  271. foreach (DictionaryEntry entry in attributes)
  272. {
  273. string thisName = entry.Key as string;
  274. int indexOfColon = thisName.IndexOf (':');
  275. if (indexOfColon != -1) {
  276. string thisLocalName = thisName.Substring (indexOfColon + 1);
  277. if (localName == thisLocalName) {
  278. string thisPrefix = thisName.Substring (0, indexOfColon);
  279. string thisNamespaceURI = LookupNamespace (thisPrefix);
  280. if (namespaceURI == thisNamespaceURI)
  281. return attributes.ContainsKey (thisName) ?
  282. UnescapeAttributeValue (attributes [thisName] as string) : String.Empty;
  283. }
  284. } else if (localName == "xmlns" && namespaceURI == "http://www.w3.org/2000/xmlns/" && thisName == "xmlns")
  285. return attributes.ContainsKey (thisName) ?
  286. UnescapeAttributeValue (attributes [thisName] as string) : String.Empty;
  287. }
  288. return String.Empty;
  289. }
  290. [MonoTODO]
  291. public TextReader GetRemainder ()
  292. {
  293. throw new NotImplementedException ();
  294. }
  295. bool IXmlLineInfo.HasLineInfo ()
  296. {
  297. return true;
  298. }
  299. public override string LookupNamespace (string prefix)
  300. {
  301. return parserContext.NamespaceManager.LookupNamespace (prefix);
  302. }
  303. public override void MoveToAttribute (int i)
  304. {
  305. MoveToElement ();
  306. if (attributes == null || orderedAttributes.Count < i || i < 0)
  307. throw new ArgumentOutOfRangeException ("attribute index out of range.");
  308. string name = orderedAttributes [i] as string;
  309. string value = attributes [name] as string;
  310. SetProperties (
  311. XmlNodeType.Attribute, // nodeType
  312. name, // name
  313. false, // isEmptyElement
  314. value, // value
  315. false // clearAttributes
  316. );
  317. attributeValuePos = 0;
  318. }
  319. public override bool MoveToAttribute (string name)
  320. {
  321. MoveToElement ();
  322. bool match = false;
  323. if (attributes == null)
  324. return false;
  325. if (orderedAttributesEnumerator == null) {
  326. SaveProperties ();
  327. orderedAttributesEnumerator = orderedAttributes.GetEnumerator ();
  328. }
  329. while (orderedAttributesEnumerator.MoveNext ()) {
  330. if(name == orderedAttributesEnumerator.Current as string) {
  331. match = true;
  332. break;
  333. }
  334. }
  335. if (match) {
  336. string value = attributes [name] as string;
  337. SetProperties (
  338. XmlNodeType.Attribute, // nodeType
  339. name, // name
  340. false, // isEmptyElement
  341. value, // value
  342. false // clearAttributes
  343. );
  344. attributeValuePos = 0;
  345. }
  346. return match;
  347. }
  348. [MonoTODO]
  349. public override bool MoveToAttribute (string localName, string namespaceName)
  350. {
  351. throw new NotImplementedException ();
  352. }
  353. public override bool MoveToElement ()
  354. {
  355. if (orderedAttributesEnumerator != null) {
  356. orderedAttributesEnumerator = null;
  357. RestoreProperties ();
  358. return true;
  359. }
  360. return false;
  361. }
  362. public override bool MoveToFirstAttribute ()
  363. {
  364. MoveToElement ();
  365. return MoveToNextAttribute ();
  366. }
  367. public override bool MoveToNextAttribute ()
  368. {
  369. if (attributes == null)
  370. return false;
  371. if (orderedAttributesEnumerator == null) {
  372. SaveProperties ();
  373. orderedAttributesEnumerator = orderedAttributes.GetEnumerator ();
  374. }
  375. if (orderedAttributesEnumerator.MoveNext ()) {
  376. string name = orderedAttributesEnumerator.Current as string;
  377. string value = attributes [name] as string;
  378. SetProperties (
  379. XmlNodeType.Attribute, // nodeType
  380. name, // name
  381. false, // isEmptyElement
  382. value, // value
  383. false // clearAttributes
  384. );
  385. attributeValuePos = 0;
  386. return true;
  387. }
  388. return false;
  389. }
  390. public override bool Read ()
  391. {
  392. bool more = false;
  393. readState = ReadState.Interactive;
  394. more = ReadContent ();
  395. return more;
  396. }
  397. public override bool ReadAttributeValue ()
  398. {
  399. // 'attributeString' holds real string value (without their
  400. // quotation characters).
  401. //
  402. // 'attributeValuePos' holds current position
  403. // of 'attributeString' while iterating ReadAttribute().
  404. // It may be:
  405. // -1 if ReadAttributeValue() has already finished.
  406. // 0 if ReadAttributeValue() ready to start reading.
  407. // >0 if ReadAttributeValue() already got 1 or more values
  408. //
  409. // local 'refPosition' holds the position on the
  410. // attributeString which may be used next time.
  411. if (attributeValuePos < 0) {
  412. SetProperties (XmlNodeType.None,
  413. String.Empty,
  414. false,
  415. String.Empty,
  416. false);
  417. return false;
  418. }
  419. // If not started, then initialize attributeString when parsing is at start.
  420. if (attributeValuePos == 0)
  421. attributeString =
  422. value.Substring (1, value.Length - 2);
  423. returnEntityReference = false;
  424. value = String.Empty;
  425. int refPosition;
  426. int loop = 0;
  427. do {
  428. refPosition = attributeString.IndexOf ('&', attributeValuePos);
  429. if (refPosition < 0) {
  430. // Reached to the end of value string.
  431. value += attributeString.Substring (attributeValuePos);
  432. attributeValuePos = -1;
  433. break;
  434. } else if (refPosition == attributeValuePos) {
  435. string parsed = ReadAttributeValueReference ();
  436. if (parsed != null)
  437. value += parsed;
  438. else {
  439. // Found that an entity reference starts from this point.
  440. // reset position to after '&'.
  441. attributeValuePos = refPosition;
  442. if (value.Length <= 0) {
  443. int endNamePos = attributeString.IndexOf (";", attributeValuePos);
  444. value = attributeString.Substring (attributeValuePos+1, endNamePos - attributeValuePos - 1);
  445. attributeValuePos += value.Length + 2;
  446. returnEntityReference = true;
  447. }
  448. break;
  449. }
  450. } else {
  451. value += attributeString.Substring (attributeValuePos,
  452. refPosition - attributeValuePos);
  453. attributeValuePos = refPosition;
  454. continue;
  455. }
  456. } while (++loop > 0);
  457. if (returnEntityReference)
  458. SetProperties (XmlNodeType.EntityReference,
  459. value,
  460. false,
  461. String.Empty,
  462. false);
  463. else
  464. SetProperties (XmlNodeType.Text,
  465. "#text",
  466. false,
  467. value,
  468. false);
  469. return true;
  470. }
  471. [MonoTODO]
  472. public int ReadBase64 (byte [] buffer, int offset, int length)
  473. {
  474. throw new NotImplementedException ();
  475. }
  476. [MonoTODO]
  477. public int ReadBinHex (byte [] buffer, int offset, int length)
  478. {
  479. throw new NotImplementedException ();
  480. }
  481. [MonoTODO]
  482. public int ReadChars (char [] buffer, int offset, int length)
  483. {
  484. throw new NotImplementedException ();
  485. }
  486. public override string ReadInnerXml ()
  487. {
  488. if (readState != ReadState.Interactive)
  489. return String.Empty;
  490. switch (NodeType) {
  491. case XmlNodeType.Attribute:
  492. return value.Substring (1, value.Length - 2);
  493. case XmlNodeType.Element:
  494. if (IsEmptyElement)
  495. return String.Empty;
  496. int startDepth = depth;
  497. innerXmlBuilder.Length = 0;
  498. do {
  499. ReadContent ();
  500. if (NodeType != XmlNodeType.EndElement || depth + 1 > startDepth)
  501. innerXmlBuilder.Append (currentTag);
  502. } while (depth >= startDepth);
  503. string xml = innerXmlBuilder.ToString ();
  504. innerXmlBuilder.Length = 0;
  505. return xml;
  506. case XmlNodeType.None:
  507. // MS document is incorrect. Seems not to progress.
  508. return String.Empty;
  509. default:
  510. Read ();
  511. return String.Empty;
  512. }
  513. }
  514. public override string ReadOuterXml ()
  515. {
  516. if (readState != ReadState.Interactive)
  517. return String.Empty;
  518. switch (NodeType) {
  519. case XmlNodeType.Attribute:
  520. // strictly incompatible with MS... (it holds spaces attribute between name, value and "=" char (very trivial).
  521. return String.Format ("{0}={1}{2}{1}", Name, QuoteChar, ReadInnerXml ());
  522. case XmlNodeType.Element:
  523. bool isEmpty = IsEmptyElement;
  524. string startTag = currentTag.ToString ();
  525. string name = Name;
  526. if (NodeType == XmlNodeType.Element && !isEmpty)
  527. return String.Format ("{0}{1}</{2}>", startTag, ReadInnerXml (), name);
  528. else
  529. return currentTag.ToString ();
  530. case XmlNodeType.None:
  531. // MS document is incorrect. Seems not to progress.
  532. return String.Empty;
  533. default:
  534. Read ();
  535. return String.Empty;
  536. }
  537. }
  538. [MonoTODO]
  539. public override string ReadString ()
  540. {
  541. throw new NotImplementedException ();
  542. }
  543. [MonoTODO]
  544. public void ResetState ()
  545. {
  546. throw new NotImplementedException ();
  547. }
  548. public override void ResolveEntity ()
  549. {
  550. // XmlTextReaders don't resolve entities.
  551. throw new InvalidOperationException ("XmlTextReader cannot resolve external entities.");
  552. }
  553. #endregion
  554. #region Internals
  555. internal string publicId;
  556. internal string systemId;
  557. internal void SetReaderContext (string url, XmlParserContext context)
  558. {
  559. parserContext = context;
  560. parserContext.BaseURI = url;
  561. Init ();
  562. }
  563. internal void SetReaderFragment(TextReader fragment, XmlNodeType fragType)
  564. {
  565. this.reader = fragment;
  566. StreamReader sr = fragment as StreamReader;
  567. if (sr != null)
  568. can_seek = sr.BaseStream.CanSeek;
  569. else
  570. can_seek = fragment != null && fragment.Peek () != -1;
  571. if (fragType == XmlNodeType.Attribute)
  572. value = "''";
  573. else if (fragType == XmlNodeType.DocumentFragment)
  574. allowMultipleRoot = true;
  575. /* for future use
  576. switch(fragType)
  577. {
  578. case XmlNodeType.Attribute: // attribute content
  579. parserContext.InputState = XmlParserInputState.AttributeValue;
  580. break;
  581. case XmlNodeType.DocumentFragment: // element content
  582. parserContext.InputState = XmlParserInputState.Content;
  583. break;
  584. case XmlNodeType.Element: // one element
  585. parserContext.InputState = XmlParserInputState.StartTag;
  586. break;
  587. case XmlNodeType.Document: // document content
  588. parserContext.InputState = XmlParserInputState.Start;
  589. break;
  590. default:
  591. throw new InvalidOperationException("setting this xml node type not allowed.");
  592. }
  593. */
  594. }
  595. #endregion
  596. #region Privates
  597. private XmlParserContext parserContext;
  598. private TextReader reader;
  599. private ReadState readState;
  600. private int depth;
  601. private int elementDepth;
  602. private bool depthDown;
  603. private bool popScope;
  604. private Stack elementStack;
  605. private bool haveEnteredDocument;
  606. private bool allowMultipleRoot = false;
  607. private XmlNodeType nodeType;
  608. private string name;
  609. private string prefix;
  610. private string localName;
  611. private string namespaceURI;
  612. private bool isEmptyElement;
  613. private string value;
  614. private XmlNodeType saveNodeType;
  615. private string saveName;
  616. private string savePrefix;
  617. private string saveLocalName;
  618. private string saveNamespaceURI;
  619. private bool saveIsEmptyElement;
  620. private Hashtable attributes;
  621. private ArrayList orderedAttributes;
  622. private IEnumerator orderedAttributesEnumerator;
  623. private bool returnEntityReference;
  624. private string entityReferenceName;
  625. private char [] nameBuffer;
  626. private int nameLength;
  627. private int nameCapacity;
  628. private const int initialNameCapacity = 256;
  629. private char [] valueBuffer;
  630. private int valueLength;
  631. private int valueCapacity;
  632. private const int initialValueCapacity = 8192;
  633. private StringBuilder currentTag; // A buffer for ReadContent for ReadOuterXml
  634. private int line = 1;
  635. private int column = 1;
  636. private bool has_peek;
  637. private bool can_seek;
  638. private int peek_char;
  639. private string attributeString = String.Empty;
  640. private int attributeValuePos;
  641. // This should be only referenced(used) by ReadInnerXml(). Kind of flyweight pattern.
  642. private StringBuilder innerXmlBuilder;
  643. private XmlException ReaderError(string message)
  644. {
  645. return new XmlException(message, LineNumber, LinePosition);
  646. }
  647. private void Init ()
  648. {
  649. readState = ReadState.Initial;
  650. depth = 0;
  651. depthDown = false;
  652. popScope = false;
  653. elementStack = new Stack();
  654. haveEnteredDocument = false;
  655. nodeType = XmlNodeType.None;
  656. name = String.Empty;
  657. prefix = String.Empty;
  658. localName = string.Empty;
  659. isEmptyElement = false;
  660. value = String.Empty;
  661. attributes = new Hashtable ();
  662. orderedAttributes = new ArrayList ();
  663. orderedAttributesEnumerator = null;
  664. returnEntityReference = false;
  665. entityReferenceName = String.Empty;
  666. nameBuffer = new char [initialNameCapacity];
  667. nameLength = 0;
  668. nameCapacity = initialNameCapacity;
  669. valueBuffer = new char [initialValueCapacity];
  670. valueLength = 0;
  671. valueCapacity = initialValueCapacity;
  672. currentTag = new StringBuilder ();
  673. innerXmlBuilder = new StringBuilder ();
  674. }
  675. // Use this method rather than setting the properties
  676. // directly so that all the necessary properties can
  677. // be changed in harmony with each other. Maybe the
  678. // fields should be in a seperate class to help enforce
  679. // this.
  680. private void SetProperties (
  681. XmlNodeType nodeType,
  682. string name,
  683. bool isEmptyElement,
  684. string value,
  685. bool clearAttributes)
  686. {
  687. this.nodeType = nodeType;
  688. this.name = name;
  689. this.isEmptyElement = isEmptyElement;
  690. this.value = value;
  691. this.elementDepth = depth;
  692. if (clearAttributes)
  693. ClearAttributes ();
  694. int indexOfColon = name.IndexOf (':');
  695. if (indexOfColon == -1) {
  696. prefix = String.Empty;
  697. localName = name;
  698. } else {
  699. prefix = name.Substring (0, indexOfColon);
  700. localName = name.Substring (indexOfColon + 1);
  701. }
  702. namespaceURI = LookupNamespace (prefix);
  703. }
  704. private void SaveProperties ()
  705. {
  706. saveNodeType = nodeType;
  707. saveName = name;
  708. savePrefix = prefix;
  709. saveLocalName = localName;
  710. saveNamespaceURI = namespaceURI;
  711. saveIsEmptyElement = isEmptyElement;
  712. // An element's value is always String.Empty.
  713. }
  714. private void RestoreProperties ()
  715. {
  716. nodeType = saveNodeType;
  717. name = saveName;
  718. prefix = savePrefix;
  719. localName = saveLocalName;
  720. namespaceURI = saveNamespaceURI;
  721. isEmptyElement = saveIsEmptyElement;
  722. value = String.Empty;
  723. }
  724. private void AddAttribute (string name, string value)
  725. {
  726. attributes.Add (name, value);
  727. orderedAttributes.Add (name);
  728. }
  729. private void ClearAttributes ()
  730. {
  731. if (attributes.Count > 0) {
  732. attributes.Clear ();
  733. orderedAttributes.Clear ();
  734. }
  735. orderedAttributesEnumerator = null;
  736. }
  737. private int PeekChar ()
  738. {
  739. if (can_seek)
  740. return reader.Peek ();
  741. if (has_peek)
  742. return peek_char;
  743. peek_char = reader.Read ();
  744. has_peek = true;
  745. return peek_char;
  746. }
  747. private int ReadChar ()
  748. {
  749. int ch;
  750. if (has_peek) {
  751. ch = peek_char;
  752. has_peek = false;
  753. } else {
  754. ch = reader.Read ();
  755. }
  756. if (ch == '\n') {
  757. line++;
  758. column = 1;
  759. } else {
  760. column++;
  761. }
  762. currentTag.Append ((char) ch);
  763. return ch;
  764. }
  765. // This should really keep track of some state so
  766. // that it's not possible to have more than one document
  767. // element or text outside of the document element.
  768. private bool ReadContent ()
  769. {
  770. currentTag.Length = 0;
  771. if (popScope) {
  772. parserContext.NamespaceManager.PopScope ();
  773. popScope = false;
  774. }
  775. if (returnEntityReference) {
  776. SetEntityReferenceProperties ();
  777. } else {
  778. switch (PeekChar ())
  779. {
  780. case '<':
  781. ReadChar ();
  782. ReadTag ();
  783. break;
  784. case '\r':
  785. if (whitespaceHandling == WhitespaceHandling.All ||
  786. whitespaceHandling == WhitespaceHandling.Significant)
  787. return ReadWhitespace ();
  788. ReadChar ();
  789. return ReadContent ();
  790. case '\n':
  791. if (whitespaceHandling == WhitespaceHandling.All ||
  792. whitespaceHandling == WhitespaceHandling.Significant)
  793. return ReadWhitespace ();
  794. ReadChar ();
  795. return ReadContent ();
  796. case ' ':
  797. if (whitespaceHandling == WhitespaceHandling.All ||
  798. whitespaceHandling == WhitespaceHandling.Significant)
  799. return ReadWhitespace ();
  800. SkipWhitespace ();
  801. return ReadContent ();
  802. case -1:
  803. readState = ReadState.EndOfFile;
  804. SetProperties (
  805. XmlNodeType.None, // nodeType
  806. String.Empty, // name
  807. false, // isEmptyElement
  808. String.Empty, // value
  809. true // clearAttributes
  810. );
  811. break;
  812. default:
  813. ReadText (true);
  814. break;
  815. }
  816. }
  817. return this.ReadState != ReadState.EndOfFile;
  818. }
  819. private void SetEntityReferenceProperties ()
  820. {
  821. SetProperties (
  822. XmlNodeType.EntityReference, // nodeType
  823. entityReferenceName, // name
  824. false, // isEmptyElement
  825. String.Empty, // value
  826. true // clearAttributes
  827. );
  828. returnEntityReference = false;
  829. entityReferenceName = String.Empty;
  830. }
  831. // The leading '<' has already been consumed.
  832. private void ReadTag ()
  833. {
  834. switch (PeekChar ())
  835. {
  836. case '/':
  837. ReadChar ();
  838. ReadEndTag ();
  839. break;
  840. case '?':
  841. ReadChar ();
  842. ReadProcessingInstruction ();
  843. break;
  844. case '!':
  845. ReadChar ();
  846. ReadDeclaration ();
  847. break;
  848. default:
  849. ReadStartTag ();
  850. break;
  851. }
  852. }
  853. // The leading '<' has already been consumed.
  854. private void ReadStartTag ()
  855. {
  856. parserContext.NamespaceManager.PushScope ();
  857. string name = ReadName ();
  858. if (haveEnteredDocument && elementStack.Count == 0 && !allowMultipleRoot)
  859. throw ReaderError("document has terminated, cannot open new element");
  860. haveEnteredDocument = true;
  861. SkipWhitespace ();
  862. bool isEmptyElement = false;
  863. ClearAttributes ();
  864. if (XmlConstructs.IsNameStart (PeekChar ()))
  865. ReadAttributes ();
  866. if (PeekChar () == '/') {
  867. ReadChar ();
  868. isEmptyElement = true;
  869. depthDown = true;
  870. popScope = true;
  871. }
  872. else
  873. elementStack.Push(name);
  874. Expect ('>');
  875. SetProperties (
  876. XmlNodeType.Element, // nodeType
  877. name, // name
  878. isEmptyElement, // isEmptyElement
  879. String.Empty, // value
  880. false // clearAttributes
  881. );
  882. if (!depthDown)
  883. ++depth;
  884. else
  885. depthDown = false;
  886. }
  887. // The reader is positioned on the first character
  888. // of the element's name.
  889. private void ReadEndTag ()
  890. {
  891. string name = ReadName ();
  892. if (elementStack.Count == 0)
  893. throw ReaderError("closing element without matching opening element");
  894. if ((string)elementStack.Pop() != name)
  895. throw ReaderError("unmatched closing element");
  896. SkipWhitespace ();
  897. Expect ('>');
  898. --depth;
  899. SetProperties (
  900. XmlNodeType.EndElement, // nodeType
  901. name, // name
  902. false, // isEmptyElement
  903. String.Empty, // value
  904. true // clearAttributes
  905. );
  906. popScope = true;
  907. }
  908. private void AppendNameChar (int ch)
  909. {
  910. CheckNameCapacity ();
  911. nameBuffer [nameLength++] = (char)ch;
  912. }
  913. private void CheckNameCapacity ()
  914. {
  915. if (nameLength == nameCapacity) {
  916. nameCapacity = nameCapacity * 2;
  917. char [] oldNameBuffer = nameBuffer;
  918. nameBuffer = new char [nameCapacity];
  919. Array.Copy (oldNameBuffer, nameBuffer, nameLength);
  920. }
  921. }
  922. private string CreateNameString ()
  923. {
  924. return new String (nameBuffer, 0, nameLength);
  925. }
  926. private void AppendValueChar (int ch)
  927. {
  928. CheckValueCapacity ();
  929. valueBuffer [valueLength++] = (char)ch;
  930. }
  931. private void CheckValueCapacity ()
  932. {
  933. if (valueLength == valueCapacity) {
  934. valueCapacity = valueCapacity * 2;
  935. char [] oldValueBuffer = valueBuffer;
  936. valueBuffer = new char [valueCapacity];
  937. Array.Copy (oldValueBuffer, valueBuffer, valueLength);
  938. }
  939. }
  940. private string CreateValueString ()
  941. {
  942. return new String (valueBuffer, 0, valueLength);
  943. }
  944. // The reader is positioned on the first character
  945. // of the text.
  946. private void ReadText (bool cleanValue)
  947. {
  948. if (cleanValue)
  949. valueLength = 0;
  950. int ch = PeekChar ();
  951. while (ch != '<' && ch != -1) {
  952. if (ch == '&') {
  953. ReadChar ();
  954. if (ReadReference (false))
  955. break;
  956. } else
  957. AppendValueChar (ReadChar ());
  958. ch = PeekChar ();
  959. }
  960. if (returnEntityReference && valueLength == 0) {
  961. SetEntityReferenceProperties ();
  962. } else {
  963. SetProperties (
  964. XmlNodeType.Text, // nodeType
  965. String.Empty, // name
  966. false, // isEmptyElement
  967. CreateValueString (), // value
  968. true // clearAttributes
  969. );
  970. }
  971. }
  972. // The leading '&' has already been consumed.
  973. // Returns true if the entity reference isn't a simple
  974. // character reference or one of the predefined entities.
  975. // This allows the ReadText method to break so that the
  976. // next call to Read will return the EntityReference node.
  977. private bool ReadReference (bool ignoreEntityReferences)
  978. {
  979. if (PeekChar () == '#') {
  980. ReadChar ();
  981. ReadCharacterReference ();
  982. } else
  983. ReadEntityReference (ignoreEntityReferences);
  984. return returnEntityReference;
  985. }
  986. private void ReadCharacterReference ()
  987. {
  988. int value = 0;
  989. if (PeekChar () == 'x') {
  990. ReadChar ();
  991. while (PeekChar () != ';' && PeekChar () != -1) {
  992. int ch = ReadChar ();
  993. if (ch >= '0' && ch <= '9')
  994. value = (value << 4) + ch - '0';
  995. else if (ch >= 'A' && ch <= 'F')
  996. value = (value << 4) + ch - 'A' + 10;
  997. else if (ch >= 'a' && ch <= 'f')
  998. value = (value << 4) + ch - 'a' + 10;
  999. else
  1000. throw ReaderError (
  1001. String.Format (
  1002. "invalid hexadecimal digit: {0} (#x{1:X})",
  1003. (char)ch,
  1004. ch));
  1005. }
  1006. } else {
  1007. while (PeekChar () != ';' && PeekChar () != -1) {
  1008. int ch = ReadChar ();
  1009. if (ch >= '0' && ch <= '9')
  1010. value = value * 10 + ch - '0';
  1011. else
  1012. throw ReaderError (
  1013. String.Format (
  1014. "invalid decimal digit: {0} (#x{1:X})",
  1015. (char)ch,
  1016. ch));
  1017. }
  1018. }
  1019. ReadChar (); // ';'
  1020. AppendValueChar (value);
  1021. }
  1022. private void ReadEntityReference (bool ignoreEntityReferences)
  1023. {
  1024. nameLength = 0;
  1025. int ch = PeekChar ();
  1026. while (ch != ';' && ch != -1) {
  1027. AppendNameChar (ReadChar ());
  1028. ch = PeekChar ();
  1029. }
  1030. Expect (';');
  1031. string name = CreateNameString ();
  1032. switch (name)
  1033. {
  1034. case "lt":
  1035. AppendValueChar ('<');
  1036. break;
  1037. case "gt":
  1038. AppendValueChar ('>');
  1039. break;
  1040. case "amp":
  1041. AppendValueChar ('&');
  1042. break;
  1043. case "apos":
  1044. AppendValueChar ('\'');
  1045. break;
  1046. case "quot":
  1047. AppendValueChar ('"');
  1048. break;
  1049. default:
  1050. if (ignoreEntityReferences) {
  1051. AppendValueChar ('&');
  1052. foreach (char ch2 in name) {
  1053. AppendValueChar (ch2);
  1054. }
  1055. AppendValueChar (';');
  1056. } else {
  1057. returnEntityReference = true;
  1058. entityReferenceName = name;
  1059. }
  1060. break;
  1061. }
  1062. }
  1063. // The reader is positioned on the first character of
  1064. // the attribute name.
  1065. private void ReadAttributes ()
  1066. {
  1067. do {
  1068. string name = ReadName ();
  1069. SkipWhitespace ();
  1070. Expect ('=');
  1071. SkipWhitespace ();
  1072. string value = ReadAttribute ();
  1073. SkipWhitespace ();
  1074. if (name == "xmlns")
  1075. parserContext.NamespaceManager.AddNamespace (String.Empty, UnescapeAttributeValue (value));
  1076. else if (name.StartsWith ("xmlns:"))
  1077. parserContext.NamespaceManager.AddNamespace (name.Substring (6), UnescapeAttributeValue (value));
  1078. AddAttribute (name, value);
  1079. } while (PeekChar () != '/' && PeekChar () != '>' && PeekChar () != -1);
  1080. }
  1081. // The reader is positioned on the quote character.
  1082. // *Keeps quote char* to value to get_QuoteChar() correctly.
  1083. private string ReadAttribute ()
  1084. {
  1085. valueLength = 0;
  1086. int quoteChar = ReadChar ();
  1087. if (quoteChar != '\'' && quoteChar != '\"')
  1088. throw ReaderError ("an attribute value was not quoted");
  1089. AppendValueChar (quoteChar);
  1090. while (PeekChar () != quoteChar) {
  1091. int ch = ReadChar ();
  1092. switch (ch)
  1093. {
  1094. case '<':
  1095. throw ReaderError ("attribute values cannot contain '<'");
  1096. case -1:
  1097. throw ReaderError ("unexpected end of file in an attribute value");
  1098. default:
  1099. AppendValueChar (ch);
  1100. break;
  1101. }
  1102. }
  1103. ReadChar (); // quoteChar
  1104. AppendValueChar (quoteChar);
  1105. return CreateValueString ();
  1106. }
  1107. // The reader is positioned on the first character
  1108. // of the target.
  1109. //
  1110. // Now it also reads XmlDeclaration, this method name became improper...
  1111. private void ReadProcessingInstruction ()
  1112. {
  1113. string target = ReadName ();
  1114. SkipWhitespace ();
  1115. valueLength = 0;
  1116. while (PeekChar () != -1) {
  1117. int ch = ReadChar ();
  1118. if (ch == '?' && PeekChar () == '>') {
  1119. ReadChar ();
  1120. break;
  1121. }
  1122. AppendValueChar ((char)ch);
  1123. }
  1124. /* for future use
  1125. if(target == "xml") && parserContext.InputState != XmlParserInputState.Start)
  1126. throw new XmlException("Xml declaration is not allowed here.");
  1127. else {
  1128. parserContext.InputState = XmlParserInputState.DTD; //for future use
  1129. }
  1130. */
  1131. SetProperties (
  1132. target == "xml" ?
  1133. XmlNodeType.XmlDeclaration :
  1134. XmlNodeType.ProcessingInstruction, // nodeType
  1135. target, // name
  1136. false, // isEmptyElement
  1137. CreateValueString (), // value
  1138. true // clearAttributes
  1139. );
  1140. }
  1141. // The reader is positioned on the first character after
  1142. // the leading '<!'.
  1143. private void ReadDeclaration ()
  1144. {
  1145. int ch = PeekChar ();
  1146. switch (ch)
  1147. {
  1148. case '-':
  1149. Expect ("--");
  1150. ReadComment ();
  1151. break;
  1152. case '[':
  1153. ReadChar ();
  1154. Expect ("CDATA[");
  1155. ReadCDATA ();
  1156. break;
  1157. case 'D':
  1158. Expect ("DOCTYPE");
  1159. ReadDoctypeDecl ();
  1160. break;
  1161. }
  1162. }
  1163. // The reader is positioned on the first character after
  1164. // the leading '<!--'.
  1165. private void ReadComment ()
  1166. {
  1167. valueLength = 0;
  1168. while (PeekChar () != -1) {
  1169. int ch = ReadChar ();
  1170. if (ch == '-' && PeekChar () == '-') {
  1171. ReadChar ();
  1172. if (PeekChar () != '>')
  1173. throw ReaderError ("comments cannot contain '--'");
  1174. ReadChar ();
  1175. break;
  1176. }
  1177. AppendValueChar ((char)ch);
  1178. }
  1179. SetProperties (
  1180. XmlNodeType.Comment, // nodeType
  1181. String.Empty, // name
  1182. false, // isEmptyElement
  1183. CreateValueString (), // value
  1184. true // clearAttributes
  1185. );
  1186. }
  1187. // The reader is positioned on the first character after
  1188. // the leading '<![CDATA['.
  1189. private void ReadCDATA ()
  1190. {
  1191. valueLength = 0;
  1192. while (PeekChar () != -1) {
  1193. int ch = ReadChar ();
  1194. if (ch == ']' && PeekChar () == ']') {
  1195. ch = ReadChar (); // ']'
  1196. if (PeekChar () == '>') {
  1197. ReadChar (); // '>'
  1198. break;
  1199. } else {
  1200. AppendValueChar (']');
  1201. AppendValueChar (']');
  1202. ch = ReadChar ();
  1203. }
  1204. }
  1205. AppendValueChar ((char)ch);
  1206. }
  1207. SetProperties (
  1208. XmlNodeType.CDATA, // nodeType
  1209. String.Empty, // name
  1210. false, // isEmptyElement
  1211. CreateValueString (), // value
  1212. true // clearAttributes
  1213. );
  1214. }
  1215. // The reader is positioned on the first character after
  1216. // the leading '<!DOCTYPE'.
  1217. private void ReadDoctypeDecl ()
  1218. {
  1219. string doctypeName = null;
  1220. string publicId = String.Empty;
  1221. string systemId = String.Empty;
  1222. SkipWhitespace ();
  1223. doctypeName = ReadName ();
  1224. SkipWhitespace ();
  1225. switch(PeekChar ())
  1226. {
  1227. case 'S':
  1228. systemId = ReadSystemLiteral (true);
  1229. break;
  1230. case 'P':
  1231. publicId = ReadPubidLiteral ();
  1232. SkipWhitespace ();
  1233. systemId = ReadSystemLiteral (false);
  1234. break;
  1235. }
  1236. SkipWhitespace ();
  1237. if(PeekChar () == '[')
  1238. {
  1239. // read markupdecl etc. or end of decl
  1240. ReadChar ();
  1241. int startPos = currentTag.Length;
  1242. do {
  1243. ReadDTDInternalSubset ();
  1244. } while (nodeType != XmlNodeType.None);
  1245. int endPos = currentTag.Length - 1;
  1246. parserContext.InternalSubset = currentTag.ToString (startPos, endPos - startPos);
  1247. }
  1248. // end of DOCTYPE decl.
  1249. SkipWhitespace ();
  1250. Expect ('>');
  1251. // set properties for <!DOCTYPE> node
  1252. SetProperties (
  1253. XmlNodeType.DocumentType, // nodeType
  1254. doctypeName, // name
  1255. false, // isEmptyElement
  1256. parserContext.InternalSubset, // value
  1257. true // clearAttributes
  1258. );
  1259. }
  1260. // Read any one of following:
  1261. // elementdecl, AttlistDecl, EntityDecl, NotationDecl,
  1262. // PI, Comment, Parameter Entity, or doctype termination char(']')
  1263. //
  1264. // returns a node of some nodeType or null, setting nodeType.
  1265. // (if None then ']' was found.)
  1266. private void ReadDTDInternalSubset()
  1267. {
  1268. SkipWhitespace ();
  1269. switch(ReadChar ())
  1270. {
  1271. case ']':
  1272. nodeType = XmlNodeType.None;
  1273. break;
  1274. case '%':
  1275. string peName = ReadName ();
  1276. Expect (';');
  1277. nodeType = XmlNodeType.EntityReference; // It's chating a bit;-)
  1278. break;
  1279. case '<':
  1280. switch(ReadChar ())
  1281. {
  1282. case '?':
  1283. ReadProcessingInstruction ();
  1284. break;
  1285. case '!':
  1286. switch(ReadChar ())
  1287. {
  1288. case '-':
  1289. Expect ('-');
  1290. ReadComment ();
  1291. break;
  1292. case 'E':
  1293. switch(ReadChar ())
  1294. {
  1295. case 'N':
  1296. Expect ("TITY");
  1297. ReadEntityDecl ();
  1298. break;
  1299. case 'L':
  1300. Expect ("EMENT");
  1301. ReadElementDecl ();
  1302. break;
  1303. default:
  1304. throw ReaderError ("Syntax Error after '<!E' (ELEMENT or ENTITY must be found)");
  1305. }
  1306. break;
  1307. case 'A':
  1308. Expect ("TTLIST");
  1309. ReadAttListDecl ();
  1310. break;
  1311. case 'N':
  1312. Expect ("OTATION");
  1313. ReadNotationDecl ();
  1314. break;
  1315. default:
  1316. throw ReaderError ("Syntax Error after '<!' characters.");
  1317. }
  1318. break;
  1319. default:
  1320. throw ReaderError ("Syntax Error after '<' character.");
  1321. }
  1322. break;
  1323. default:
  1324. throw ReaderError ("Syntax Error inside doctypedecl markup.");
  1325. }
  1326. }
  1327. // The reader is positioned on the head of the name.
  1328. private void ReadElementDecl()
  1329. {
  1330. while(ReadChar () != '>');
  1331. }
  1332. private void ReadEntityDecl()
  1333. {
  1334. while(ReadChar () != '>');
  1335. }
  1336. private void ReadAttListDecl()
  1337. {
  1338. while(ReadChar () != '>');
  1339. }
  1340. private void ReadNotationDecl()
  1341. {
  1342. while(ReadChar () != '>');
  1343. }
  1344. // The reader is positioned on the first 'S' of "SYSTEM".
  1345. private string ReadSystemLiteral (bool expectSYSTEM)
  1346. {
  1347. if(expectSYSTEM)
  1348. Expect ("SYSTEM");
  1349. SkipWhitespace ();
  1350. int quoteChar = ReadChar (); // apos or quot
  1351. int startPos = currentTag.Length;
  1352. int c = 0;
  1353. while(c != quoteChar) {
  1354. c = ReadChar ();
  1355. if(c < 0) throw ReaderError ("Unexpected end of stream in ExternalID.");
  1356. }
  1357. return currentTag.ToString (startPos, currentTag.Length - 1 - startPos);
  1358. }
  1359. private string ReadPubidLiteral()
  1360. {
  1361. Expect ("PUBLIC");
  1362. SkipWhitespace ();
  1363. int quoteChar = ReadChar ();
  1364. int startPos = currentTag.Length;
  1365. int c = 0;
  1366. while(c != quoteChar)
  1367. {
  1368. c = ReadChar ();
  1369. if(c < 0) throw ReaderError ("Unexpected end of stream in ExternalID.");
  1370. if(c != quoteChar && !XmlConstructs.IsPubid (c))
  1371. throw ReaderError("character '" + (char)c + "' not allowed for PUBLIC ID");
  1372. }
  1373. ReadChar(); // skips quoteChar
  1374. return currentTag.ToString (startPos, currentTag.Length - 1 - startPos);
  1375. }
  1376. // The reader is positioned on the first character
  1377. // of the name.
  1378. private string ReadName ()
  1379. {
  1380. if (!XmlConstructs.IsNameStart (PeekChar ()))
  1381. throw ReaderError ("a name did not start with a legal character" + PeekChar ());
  1382. nameLength = 0;
  1383. AppendNameChar (ReadChar ());
  1384. while (XmlConstructs.IsName (PeekChar ())) {
  1385. AppendNameChar (ReadChar ());
  1386. }
  1387. return CreateNameString ();
  1388. }
  1389. // Read the next character and compare it against the
  1390. // specified character.
  1391. private void Expect (int expected)
  1392. {
  1393. int ch = ReadChar ();
  1394. if (ch != expected) {
  1395. throw ReaderError (
  1396. String.Format (
  1397. "expected '{0}' ({1:X}) but found '{2}' ({3:X})",
  1398. (char)expected,
  1399. expected,
  1400. (char)ch,
  1401. ch));
  1402. }
  1403. }
  1404. private void Expect (string expected)
  1405. {
  1406. int len = expected.Length;
  1407. for(int i=0; i< len; i++)
  1408. Expect (expected[i]);
  1409. }
  1410. // Does not consume the first non-whitespace character.
  1411. private void SkipWhitespace ()
  1412. {
  1413. //FIXME: Should not skip if whitespaceHandling == WhiteSpaceHandling.None
  1414. while (XmlConstructs.IsSpace (PeekChar ()))
  1415. ReadChar ();
  1416. }
  1417. private bool ReadWhitespace ()
  1418. {
  1419. valueLength = 0;
  1420. int ch = PeekChar ();
  1421. do {
  1422. AppendValueChar (ReadChar ());
  1423. } while ((ch = PeekChar ()) != -1 && XmlConstructs.IsSpace (ch));
  1424. if (ch != -1 && ch != '<')
  1425. ReadText (false);
  1426. else
  1427. SetProperties (XmlNodeType.Whitespace,
  1428. String.Empty,
  1429. false,
  1430. CreateValueString (),
  1431. true);
  1432. return (PeekChar () != -1);
  1433. }
  1434. // read entity reference from attribute string and if parsable then return the value.
  1435. private string ReadAttributeValueReference ()
  1436. {
  1437. int endEntityPosition = attributeString.IndexOf(';',
  1438. attributeValuePos);
  1439. string entityName = attributeString.Substring (attributeValuePos + 1,
  1440. endEntityPosition - attributeValuePos - 1);
  1441. attributeValuePos = endEntityPosition + 1;
  1442. if(entityName [0] == '#') {
  1443. char c;
  1444. // character entity
  1445. if(entityName [1] == 'x') {
  1446. // hexadecimal
  1447. c = (char) int.Parse ("0" + entityName.Substring (2),
  1448. System.Globalization.NumberStyles.HexNumber);
  1449. } else {
  1450. // decimal
  1451. c = (char) int.Parse (entityName.Substring (1));
  1452. }
  1453. return c.ToString();
  1454. }
  1455. else {
  1456. switch(entityName)
  1457. {
  1458. case "lt": return "<";
  1459. case "gt": return ">";
  1460. case "amp": return "&";
  1461. case "quot": return "\"";
  1462. case "apos": return "'";
  1463. default: return null;
  1464. }
  1465. }
  1466. }
  1467. private string UnescapeAttributeValue (string unresolved)
  1468. {
  1469. if(unresolved == null) return null;
  1470. StringBuilder resolved = new StringBuilder();
  1471. int pos = 0;
  1472. // trim start/end edge of quotation character.
  1473. unresolved = unresolved.Substring (1, unresolved.Length - 2);
  1474. int next = unresolved.IndexOf ('&');
  1475. if(next < 0)
  1476. return unresolved;
  1477. while(next >= 0) {
  1478. if(pos < next)
  1479. resolved.Append (unresolved.Substring (pos, next - pos));// - 1);
  1480. int endPos = unresolved.IndexOf (';', next+1);
  1481. string entityName =
  1482. unresolved.Substring (next + 1, endPos - next - 1);
  1483. if(entityName [0] == '#') {
  1484. char c;
  1485. // character entity
  1486. if(entityName [1] == 'x') {
  1487. // hexadecimal
  1488. c = (char) int.Parse ("0" + entityName.Substring (2),
  1489. System.Globalization.NumberStyles.HexNumber);
  1490. } else {
  1491. // decimal
  1492. c = (char) int.Parse (entityName.Substring (1));
  1493. }
  1494. resolved.Append (c);
  1495. } else {
  1496. switch(entityName) {
  1497. case "lt": resolved.Append ("<"); break;
  1498. case "gt": resolved.Append (">"); break;
  1499. case "amp": resolved.Append ("&"); break;
  1500. case "quot": resolved.Append ("\""); break;
  1501. case "apos": resolved.Append ("'"); break;
  1502. // With respect to "Value", MS document is helpless
  1503. // and the implemention returns inconsistent value
  1504. // (e.g. XML: "&ent; &amp;ent;" ---> Value: "&ent; &ent;".)
  1505. default: resolved.Append ("&" + entityName + ";"); break;
  1506. }
  1507. }
  1508. pos = endPos + 1;
  1509. if(pos > unresolved.Length)
  1510. break;
  1511. next = unresolved.IndexOf('&', pos);
  1512. }
  1513. resolved.Append (unresolved.Substring(pos));
  1514. return resolved.ToString();
  1515. }
  1516. #endregion
  1517. }
  1518. }