XmlTextReader.cs 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916
  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. }
  1910. // The reader is positioned on the first character after
  1911. // the leading '<!'.
  1912. private void ReadDeclaration ()
  1913. {
  1914. int ch = PeekChar ();
  1915. switch (ch)
  1916. {
  1917. case '-':
  1918. Expect ("--");
  1919. ReadComment ();
  1920. break;
  1921. case '[':
  1922. ReadChar ();
  1923. Expect ("CDATA[");
  1924. ReadCDATA ();
  1925. break;
  1926. case 'D':
  1927. Expect ("DOCTYPE");
  1928. ReadDoctypeDecl ();
  1929. break;
  1930. default:
  1931. throw NotWFError ("Unexpected declaration markup was found.");
  1932. }
  1933. }
  1934. // The reader is positioned on the first character after
  1935. // the leading '<!--'.
  1936. private void ReadComment ()
  1937. {
  1938. if (currentState == XmlNodeType.None)
  1939. currentState = XmlNodeType.XmlDeclaration;
  1940. preserveCurrentTag = false;
  1941. ClearValueBuffer ();
  1942. int ch;
  1943. while ((ch = PeekChar ()) != -1) {
  1944. Advance (ch);
  1945. if (ch == '-' && PeekChar () == '-') {
  1946. Advance ('-');
  1947. if (PeekChar () != '>')
  1948. throw NotWFError ("comments cannot contain '--'");
  1949. Advance ('>');
  1950. break;
  1951. }
  1952. if (XmlChar.IsInvalid (ch))
  1953. throw NotWFError ("Not allowed character was found.");
  1954. AppendValueChar (ch);
  1955. }
  1956. SetProperties (
  1957. XmlNodeType.Comment, // nodeType
  1958. String.Empty, // name
  1959. String.Empty, // prefix
  1960. String.Empty, // localName
  1961. false, // isEmptyElement
  1962. null, // value: create only when required
  1963. true // clearAttributes
  1964. );
  1965. }
  1966. // The reader is positioned on the first character after
  1967. // the leading '<![CDATA['.
  1968. private void ReadCDATA ()
  1969. {
  1970. if (currentState != XmlNodeType.Element)
  1971. throw NotWFError ("CDATA section cannot appear in this state.");
  1972. preserveCurrentTag = false;
  1973. ClearValueBuffer ();
  1974. bool skip = false;
  1975. int ch = 0;
  1976. while (PeekChar () != -1) {
  1977. if (!skip)
  1978. ch = ReadChar ();
  1979. skip = false;
  1980. if (ch == ']' && PeekChar () == ']') {
  1981. ch = ReadChar (); // ']'
  1982. if (PeekChar () == '>') {
  1983. ReadChar (); // '>'
  1984. break;
  1985. } else {
  1986. skip = true;
  1987. }
  1988. }
  1989. if (normalization && ch == '\r') {
  1990. ch = PeekChar ();
  1991. if (ch != '\n')
  1992. // append '\n' instead of '\r'.
  1993. AppendValueChar ('\n');
  1994. // otherwise, discard '\r'.
  1995. continue;
  1996. }
  1997. if (CharacterChecking && XmlChar.IsInvalid (ch))
  1998. throw NotWFError ("Invalid character was found.");
  1999. // FIXME: it might be optimized by the JIT later,
  2000. // AppendValueChar (ch);
  2001. {
  2002. if (ch < Char.MaxValue)
  2003. valueBuffer.Append ((char) ch);
  2004. else
  2005. AppendSurrogatePairValueChar (ch);
  2006. }
  2007. }
  2008. SetProperties (
  2009. XmlNodeType.CDATA, // nodeType
  2010. String.Empty, // name
  2011. String.Empty, // prefix
  2012. String.Empty, // localName
  2013. false, // isEmptyElement
  2014. null, // value: create only when required
  2015. true // clearAttributes
  2016. );
  2017. }
  2018. // The reader is positioned on the first character after
  2019. // the leading '<!DOCTYPE'.
  2020. private void ReadDoctypeDecl ()
  2021. {
  2022. if (prohibitDtd)
  2023. throw NotWFError ("Document Type Declaration (DTD) is prohibited in this XML.");
  2024. switch (currentState) {
  2025. case XmlNodeType.DocumentType:
  2026. case XmlNodeType.Element:
  2027. case XmlNodeType.EndElement:
  2028. throw NotWFError ("Document type cannot appear in this state.");
  2029. }
  2030. currentState = XmlNodeType.DocumentType;
  2031. string doctypeName = null;
  2032. string publicId = null;
  2033. string systemId = null;
  2034. int intSubsetStartLine = 0;
  2035. int intSubsetStartColumn = 0;
  2036. SkipWhitespace ();
  2037. doctypeName = ReadName ();
  2038. SkipWhitespace ();
  2039. switch(PeekChar ())
  2040. {
  2041. case 'S':
  2042. systemId = ReadSystemLiteral (true);
  2043. break;
  2044. case 'P':
  2045. publicId = ReadPubidLiteral ();
  2046. if (!SkipWhitespace ())
  2047. throw NotWFError ("Whitespace is required between PUBLIC id and SYSTEM id.");
  2048. systemId = ReadSystemLiteral (false);
  2049. break;
  2050. }
  2051. SkipWhitespace ();
  2052. if(PeekChar () == '[')
  2053. {
  2054. // read markupdecl etc. or end of decl
  2055. ReadChar ();
  2056. intSubsetStartLine = this.LineNumber;
  2057. intSubsetStartColumn = this.LinePosition;
  2058. ClearValueBuffer ();
  2059. ReadInternalSubset ();
  2060. parserContext.InternalSubset = CreateValueString ();
  2061. }
  2062. // end of DOCTYPE decl.
  2063. ExpectAfterWhitespace ('>');
  2064. GenerateDTDObjectModel (doctypeName, publicId,
  2065. systemId, parserContext.InternalSubset,
  2066. intSubsetStartLine, intSubsetStartColumn);
  2067. // set properties for <!DOCTYPE> node
  2068. SetProperties (
  2069. XmlNodeType.DocumentType, // nodeType
  2070. doctypeName, // name
  2071. String.Empty, // prefix
  2072. doctypeName, // localName
  2073. false, // isEmptyElement
  2074. parserContext.InternalSubset, // value
  2075. true // clearAttributes
  2076. );
  2077. if (publicId != null)
  2078. AddAttributeWithValue ("PUBLIC", publicId);
  2079. if (systemId != null)
  2080. AddAttributeWithValue ("SYSTEM", systemId);
  2081. currentAttribute = currentAttributeValue = -1;
  2082. }
  2083. internal DTDObjectModel GenerateDTDObjectModel (string name, string publicId,
  2084. string systemId, string internalSubset)
  2085. {
  2086. return GenerateDTDObjectModel (name, publicId, systemId, internalSubset, 0, 0);
  2087. }
  2088. internal DTDObjectModel GenerateDTDObjectModel (string name, string publicId,
  2089. string systemId, string internalSubset, int intSubsetStartLine, int intSubsetStartColumn)
  2090. {
  2091. // now compile DTD
  2092. parserContext.Dtd = new DTDObjectModel (this.NameTable); // merges both internal and external subsets in the meantime,
  2093. DTD.BaseURI = BaseURI;
  2094. DTD.Name = name;
  2095. DTD.PublicId = publicId;
  2096. DTD.SystemId = systemId;
  2097. DTD.InternalSubset = internalSubset;
  2098. DTD.XmlResolver = resolver;
  2099. DTD.IsStandalone = isStandalone;
  2100. DTD.LineNumber = line;
  2101. DTD.LinePosition = column;
  2102. DTDReader dr = new DTDReader (DTD, intSubsetStartLine, intSubsetStartColumn);
  2103. dr.Normalization = this.normalization;
  2104. return dr.GenerateDTDObjectModel ();
  2105. }
  2106. private enum DtdInputState
  2107. {
  2108. Free = 1,
  2109. ElementDecl,
  2110. AttlistDecl,
  2111. EntityDecl,
  2112. NotationDecl,
  2113. PI,
  2114. Comment,
  2115. InsideSingleQuoted,
  2116. InsideDoubleQuoted,
  2117. }
  2118. private class DtdInputStateStack
  2119. {
  2120. Stack intern = new Stack ();
  2121. public DtdInputStateStack ()
  2122. {
  2123. Push (DtdInputState.Free);
  2124. }
  2125. public DtdInputState Peek ()
  2126. {
  2127. return (DtdInputState) intern.Peek ();
  2128. }
  2129. public DtdInputState Pop ()
  2130. {
  2131. return (DtdInputState) intern.Pop ();
  2132. }
  2133. public void Push (DtdInputState val)
  2134. {
  2135. intern.Push (val);
  2136. }
  2137. }
  2138. DtdInputStateStack stateStack = new DtdInputStateStack ();
  2139. DtdInputState State {
  2140. get { return stateStack.Peek (); }
  2141. }
  2142. private int ReadValueChar ()
  2143. {
  2144. int ret = ReadChar ();
  2145. AppendValueChar (ret);
  2146. return ret;
  2147. }
  2148. private void ExpectAndAppend (string s)
  2149. {
  2150. Expect (s);
  2151. valueBuffer.Append (s);
  2152. }
  2153. // Simply read but not generate any result.
  2154. private void ReadInternalSubset ()
  2155. {
  2156. bool continueParse = true;
  2157. while (continueParse) {
  2158. switch (ReadValueChar ()) {
  2159. case ']':
  2160. switch (State) {
  2161. case DtdInputState.Free:
  2162. // chop extra ']'
  2163. valueBuffer.Remove (valueBuffer.Length - 1, 1);
  2164. continueParse = false;
  2165. break;
  2166. case DtdInputState.InsideDoubleQuoted:
  2167. continue;
  2168. case DtdInputState.InsideSingleQuoted:
  2169. continue;
  2170. default:
  2171. throw NotWFError ("unexpected end of file at DTD.");
  2172. }
  2173. break;
  2174. case -1:
  2175. throw NotWFError ("unexpected end of file at DTD.");
  2176. case '<':
  2177. switch (State) {
  2178. case DtdInputState.InsideDoubleQuoted:
  2179. case DtdInputState.InsideSingleQuoted:
  2180. case DtdInputState.Comment:
  2181. continue; // well-formed
  2182. }
  2183. int c = ReadValueChar ();
  2184. switch (c) {
  2185. case '?':
  2186. stateStack.Push (DtdInputState.PI);
  2187. break;
  2188. case '!':
  2189. switch (ReadValueChar ()) {
  2190. case 'E':
  2191. switch (ReadValueChar ()) {
  2192. case 'L':
  2193. ExpectAndAppend ("EMENT");
  2194. stateStack.Push (DtdInputState.ElementDecl);
  2195. break;
  2196. case 'N':
  2197. ExpectAndAppend ("TITY");
  2198. stateStack.Push (DtdInputState.EntityDecl);
  2199. break;
  2200. default:
  2201. throw NotWFError ("unexpected token '<!E'.");
  2202. }
  2203. break;
  2204. case 'A':
  2205. ExpectAndAppend ("TTLIST");
  2206. stateStack.Push (DtdInputState.AttlistDecl);
  2207. break;
  2208. case 'N':
  2209. ExpectAndAppend ("OTATION");
  2210. stateStack.Push (DtdInputState.NotationDecl);
  2211. break;
  2212. case '-':
  2213. ExpectAndAppend ("-");
  2214. stateStack.Push (DtdInputState.Comment);
  2215. break;
  2216. }
  2217. break;
  2218. default:
  2219. throw NotWFError (String.Format ("unexpected '<{0}'.", (char) c));
  2220. }
  2221. break;
  2222. case '\'':
  2223. if (State == DtdInputState.InsideSingleQuoted)
  2224. stateStack.Pop ();
  2225. else if (State != DtdInputState.InsideDoubleQuoted && State != DtdInputState.Comment)
  2226. stateStack.Push (DtdInputState.InsideSingleQuoted);
  2227. break;
  2228. case '"':
  2229. if (State == DtdInputState.InsideDoubleQuoted)
  2230. stateStack.Pop ();
  2231. else if (State != DtdInputState.InsideSingleQuoted && State != DtdInputState.Comment)
  2232. stateStack.Push (DtdInputState.InsideDoubleQuoted);
  2233. break;
  2234. case '>':
  2235. switch (State) {
  2236. case DtdInputState.ElementDecl:
  2237. goto case DtdInputState.NotationDecl;
  2238. case DtdInputState.AttlistDecl:
  2239. goto case DtdInputState.NotationDecl;
  2240. case DtdInputState.EntityDecl:
  2241. goto case DtdInputState.NotationDecl;
  2242. case DtdInputState.NotationDecl:
  2243. stateStack.Pop ();
  2244. break;
  2245. case DtdInputState.InsideDoubleQuoted:
  2246. case DtdInputState.InsideSingleQuoted:
  2247. case DtdInputState.Comment:
  2248. continue;
  2249. default:
  2250. throw NotWFError ("unexpected token '>'");
  2251. }
  2252. break;
  2253. case '?':
  2254. if (State == DtdInputState.PI) {
  2255. if (ReadValueChar () == '>')
  2256. stateStack.Pop ();
  2257. }
  2258. break;
  2259. case '-':
  2260. if (State == DtdInputState.Comment) {
  2261. if (PeekChar () == '-') {
  2262. ReadValueChar ();
  2263. ExpectAndAppend (">");
  2264. stateStack.Pop ();
  2265. }
  2266. }
  2267. break;
  2268. case '%':
  2269. if (State != DtdInputState.Free && State != DtdInputState.EntityDecl && State != DtdInputState.Comment && State != DtdInputState.InsideDoubleQuoted && State != DtdInputState.InsideSingleQuoted)
  2270. throw NotWFError ("Parameter Entity Reference cannot appear as a part of markupdecl (see XML spec 2.8).");
  2271. break;
  2272. }
  2273. }
  2274. }
  2275. // The reader is positioned on the first 'S' of "SYSTEM".
  2276. private string ReadSystemLiteral (bool expectSYSTEM)
  2277. {
  2278. if(expectSYSTEM) {
  2279. Expect ("SYSTEM");
  2280. if (!SkipWhitespace ())
  2281. throw NotWFError ("Whitespace is required after 'SYSTEM'.");
  2282. }
  2283. else
  2284. SkipWhitespace ();
  2285. int quoteChar = ReadChar (); // apos or quot
  2286. int c = 0;
  2287. ClearValueBuffer ();
  2288. while (c != quoteChar) {
  2289. c = ReadChar ();
  2290. if (c < 0)
  2291. throw NotWFError ("Unexpected end of stream in ExternalID.");
  2292. if (c != quoteChar)
  2293. AppendValueChar (c);
  2294. }
  2295. return CreateValueString ();
  2296. }
  2297. private string ReadPubidLiteral()
  2298. {
  2299. Expect ("PUBLIC");
  2300. if (!SkipWhitespace ())
  2301. throw NotWFError ("Whitespace is required after 'PUBLIC'.");
  2302. int quoteChar = ReadChar ();
  2303. int c = 0;
  2304. ClearValueBuffer ();
  2305. while(c != quoteChar)
  2306. {
  2307. c = ReadChar ();
  2308. if(c < 0) throw NotWFError ("Unexpected end of stream in ExternalID.");
  2309. if(c != quoteChar && !XmlChar.IsPubidChar (c))
  2310. throw NotWFError (String.Format ("character '{0}' not allowed for PUBLIC ID", (char)c ));
  2311. if (c != quoteChar)
  2312. AppendValueChar (c);
  2313. }
  2314. return CreateValueString ();
  2315. }
  2316. // The reader is positioned on the first character
  2317. // of the name.
  2318. private string ReadName ()
  2319. {
  2320. string prefix, local;
  2321. return ReadName (out prefix, out local);
  2322. }
  2323. private string ReadName (out string prefix, out string localName)
  2324. {
  2325. #if !USE_NAME_BUFFER
  2326. bool savePreserve = preserveCurrentTag;
  2327. preserveCurrentTag = true;
  2328. int startOffset = peekCharsIndex - curNodePeekIndex;
  2329. int ch = PeekChar ();
  2330. if (!XmlChar.IsFirstNameChar (ch))
  2331. throw NotWFError (String.Format (CultureInfo.InvariantCulture, "a name did not start with a legal character {0} ({1})", ch, (char) ch));
  2332. Advance (ch);
  2333. int length = 1;
  2334. int colonAt = -1;
  2335. while (XmlChar.IsNameChar ((ch = PeekChar ()))) {
  2336. Advance (ch);
  2337. if (ch == ':' && namespaces && colonAt < 0)
  2338. colonAt = length;
  2339. length++;
  2340. }
  2341. int start = curNodePeekIndex + startOffset;
  2342. string name = parserContext.NameTable.Add (
  2343. peekChars, start, length);
  2344. if (colonAt > 0) {
  2345. prefix = parserContext.NameTable.Add (
  2346. peekChars, start, colonAt);
  2347. localName = parserContext.NameTable.Add (
  2348. peekChars, start + colonAt + 1, length - colonAt - 1);
  2349. } else {
  2350. prefix = String.Empty;
  2351. localName = name;
  2352. }
  2353. preserveCurrentTag = savePreserve;
  2354. return name;
  2355. #else
  2356. int ch = PeekChar ();
  2357. if (!XmlChar.IsFirstNameChar (ch))
  2358. throw NotWFError (String.Format (CultureInfo.InvariantCulture, "a name did not start with a legal character {0} ({1})", ch, (char) ch));
  2359. nameLength = 0;
  2360. Advance (ch);
  2361. // AppendNameChar (ch);
  2362. {
  2363. // nameBuffer.Length is always non-0 so no need to ExpandNameCapacity () here
  2364. if (ch < Char.MaxValue)
  2365. nameBuffer [nameLength++] = (char) ch;
  2366. else
  2367. AppendSurrogatePairNameChar (ch);
  2368. }
  2369. int colonAt = -1;
  2370. while (XmlChar.IsNameChar ((ch = PeekChar ()))) {
  2371. Advance (ch);
  2372. if (ch == ':' && namespaces && colonAt < 0)
  2373. colonAt = nameLength;
  2374. // AppendNameChar (ch);
  2375. {
  2376. if (nameLength == nameCapacity)
  2377. ExpandNameCapacity ();
  2378. if (ch < Char.MaxValue)
  2379. nameBuffer [nameLength++] = (char) ch;
  2380. else
  2381. AppendSurrogatePairNameChar (ch);
  2382. }
  2383. }
  2384. string name = parserContext.NameTable.Add (nameBuffer, 0, nameLength);
  2385. if (colonAt > 0) {
  2386. prefix = parserContext.NameTable.Add (nameBuffer, 0, colonAt);
  2387. localName = parserContext.NameTable.Add (nameBuffer, colonAt + 1, nameLength - colonAt - 1);
  2388. } else {
  2389. prefix = String.Empty;
  2390. localName = name;
  2391. }
  2392. return name;
  2393. #endif
  2394. }
  2395. // Read the next character and compare it against the
  2396. // specified character.
  2397. private void Expect (int expected)
  2398. {
  2399. int ch = ReadChar ();
  2400. if (ch != expected) {
  2401. throw NotWFError (String.Format (CultureInfo.InvariantCulture,
  2402. "expected '{0}' ({1:X}) but found '{2}' ({3:X})",
  2403. (char) expected,
  2404. expected,
  2405. ch < 0 ? (object) "EOF" : (char) ch,
  2406. ch));
  2407. }
  2408. }
  2409. private void Expect (string expected)
  2410. {
  2411. for (int i = 0; i < expected.Length; i++)
  2412. if (ReadChar () != expected [i])
  2413. throw NotWFError (String.Format (CultureInfo.InvariantCulture,
  2414. "'{0}' is expected", expected));
  2415. }
  2416. private void ExpectAfterWhitespace (char c)
  2417. {
  2418. while (true) {
  2419. int i = ReadChar ();
  2420. if (i < 0x21 && XmlChar.IsWhitespace (i))
  2421. continue;
  2422. if (c != i)
  2423. throw NotWFError (String.Format (CultureInfo.InvariantCulture, "Expected {0}, but found {1} [{2}]", c, i < 0 ? (object) "EOF" : (char) i, i));
  2424. break;
  2425. }
  2426. }
  2427. // Does not consume the first non-whitespace character.
  2428. private bool SkipWhitespace ()
  2429. {
  2430. // FIXME: It should be inlined by the JIT.
  2431. // bool skipped = XmlChar.IsWhitespace (PeekChar ());
  2432. int ch = PeekChar ();
  2433. bool skipped = (ch == 0x20 || ch == 0x9 || ch == 0xA || ch == 0xD);
  2434. if (!skipped)
  2435. return false;
  2436. Advance (ch);
  2437. // FIXME: It should be inlined by the JIT.
  2438. // while (XmlChar.IsWhitespace (PeekChar ()))
  2439. // ReadChar ();
  2440. while ((ch = PeekChar ()) == 0x20 || ch == 0x9 || ch == 0xA || ch == 0xD)
  2441. Advance (ch);
  2442. return skipped;
  2443. }
  2444. private bool ReadWhitespace ()
  2445. {
  2446. if (currentState == XmlNodeType.None)
  2447. currentState = XmlNodeType.XmlDeclaration;
  2448. bool savePreserve = preserveCurrentTag;
  2449. preserveCurrentTag = true;
  2450. int startOffset = peekCharsIndex - curNodePeekIndex; // it should be 0 for now though.
  2451. int ch = PeekChar ();
  2452. do {
  2453. Advance (ch);
  2454. ch = PeekChar ();
  2455. // FIXME: It should be inlined by the JIT.
  2456. // } while ((ch = PeekChar ()) != -1 && XmlChar.IsWhitespace (ch));
  2457. } while (ch == 0x20 || ch == 0x9 || ch == 0xA || ch == 0xD);
  2458. bool isText = currentState == XmlNodeType.Element && ch != -1 && ch != '<';
  2459. if (!isText && (whitespaceHandling == WhitespaceHandling.None ||
  2460. whitespaceHandling == WhitespaceHandling.Significant && XmlSpace != XmlSpace.Preserve))
  2461. return false;
  2462. ClearValueBuffer ();
  2463. valueBuffer.Append (peekChars, curNodePeekIndex, peekCharsIndex - curNodePeekIndex - startOffset);
  2464. preserveCurrentTag = savePreserve;
  2465. if (isText) {
  2466. ReadText (false);
  2467. } else {
  2468. XmlNodeType nodeType = (this.XmlSpace == XmlSpace.Preserve) ?
  2469. XmlNodeType.SignificantWhitespace : XmlNodeType.Whitespace;
  2470. SetProperties (nodeType,
  2471. String.Empty,
  2472. String.Empty,
  2473. String.Empty,
  2474. false,
  2475. null, // value: create only when required
  2476. true);
  2477. }
  2478. return true;
  2479. }
  2480. // Returns -1 if it should throw an error.
  2481. private int ReadCharsInternal (char [] buffer, int offset, int length)
  2482. {
  2483. shouldSkipUntilEndTag = true;
  2484. int bufIndex = offset;
  2485. for (int i = 0; i < length; i++) {
  2486. int c = PeekChar ();
  2487. switch (c) {
  2488. case -1:
  2489. throw NotWFError ("Unexpected end of xml.");
  2490. case '<':
  2491. Advance (c);
  2492. if (PeekChar () != '/') {
  2493. buffer [bufIndex++] = '<';
  2494. continue;
  2495. }
  2496. // Seems to skip immediate EndElement
  2497. Expect ('/');
  2498. if (depthUp) {
  2499. depth++;
  2500. depthUp = false;
  2501. }
  2502. ReadEndTag ();
  2503. shouldSkipUntilEndTag = false;
  2504. Read (); // move to the next node
  2505. return i;
  2506. default:
  2507. Advance (c);
  2508. if (c < Char.MaxValue)
  2509. buffer [bufIndex++] = (char) c;
  2510. else {
  2511. buffer [bufIndex++] = (char) ((c - 0x10000) / 0x400 + 0xD800);
  2512. buffer [bufIndex++] = (char) ((c - 0x10000) % 0x400 + 0xDC00);
  2513. }
  2514. break;
  2515. }
  2516. }
  2517. return length;
  2518. }
  2519. private bool ReadUntilEndTag ()
  2520. {
  2521. if (Depth == 0)
  2522. currentState = XmlNodeType.EndElement;
  2523. int ch;
  2524. do {
  2525. ch = ReadChar ();
  2526. switch (ch) {
  2527. case -1:
  2528. throw NotWFError ("Unexpected end of xml.");
  2529. case '<':
  2530. if (PeekChar () != '/')
  2531. continue;
  2532. ReadChar ();
  2533. string name = ReadName ();
  2534. if (name != elementNames [elementNameStackPos - 1].Name)
  2535. continue;
  2536. Expect ('>');
  2537. depth--;
  2538. return Read ();
  2539. }
  2540. } while (true);
  2541. }
  2542. #endregion
  2543. }
  2544. }