XmlTextReader.cs 77 KB

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