XmlTextReader.cs 77 KB

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