XmlTextReader.cs 81 KB

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