XmlTextReader.cs 76 KB

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