XmlTextReader.cs 64 KB

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