XmlTextReader.cs 65 KB

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