XmlTextReader.cs 69 KB

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