XmlTextReader.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761
  1. //
  2. // System.Xml.XmlTextReader
  3. //
  4. // Author:
  5. // Jason Diamond ([email protected])
  6. // Adam Treat ([email protected])
  7. //
  8. // (C) 2001, 2002 Jason Diamond http://injektilo.org/
  9. //
  10. // FIXME:
  11. // This can only parse basic XML: elements, attributes, processing
  12. // instructions, and comments are OK.
  13. //
  14. // It barfs on DOCTYPE declarations.
  15. // => No barfing, but parsing is incomplete.
  16. // DTD nodes are not still created.
  17. //
  18. // There's also no checking being done for either well-formedness
  19. // or validity.
  20. //
  21. // NameTables aren't being used everywhere yet.
  22. //
  23. // Some thought needs to be given to performance. There's too many
  24. // strings being allocated.
  25. //
  26. // Some of the MoveTo methods haven't been implemented yet.
  27. //
  28. // LineNumber and LinePosition aren't being tracked.
  29. //
  30. // xml:space, xml:lang, and xml:base aren't being tracked.
  31. //
  32. using System;
  33. using System.Collections;
  34. using System.IO;
  35. using System.Text;
  36. namespace System.Xml
  37. {
  38. public class XmlTextReader : XmlReader, IXmlLineInfo
  39. {
  40. WhitespaceHandling whitespaceHandling = WhitespaceHandling.All;
  41. #region Constructors
  42. protected XmlTextReader ()
  43. {
  44. }
  45. public XmlTextReader (Stream input)
  46. : this (new StreamReader (input))
  47. {
  48. }
  49. public XmlTextReader (string url)
  50. : this(url, new NameTable ())
  51. {
  52. }
  53. public XmlTextReader (TextReader input)
  54. : this (input, new NameTable ())
  55. {
  56. }
  57. protected XmlTextReader (XmlNameTable nt)
  58. : this (String.Empty, null, XmlNodeType.None, null)
  59. {
  60. }
  61. public XmlTextReader (Stream input, XmlNameTable nt)
  62. : this(new StreamReader (input), nt)
  63. {
  64. }
  65. public XmlTextReader (string url, Stream input)
  66. : this (url, new StreamReader (input))
  67. {
  68. }
  69. public XmlTextReader (string url, TextReader input)
  70. : this (url, input, new NameTable ())
  71. {
  72. }
  73. [MonoTODO("Non-filename-url must be supported. Waiting for WebClient")]
  74. public XmlTextReader (string url, XmlNameTable nt)
  75. // : this(url, new StreamReader ((Stream)new XmlUrlResolver ().GetEntity (new Uri (url), null, typeof(Stream))), nt)
  76. : this (url, new StreamReader (url), nt)
  77. {
  78. }
  79. public XmlTextReader (TextReader input, XmlNameTable nt)
  80. : this(String.Empty, input, nt)
  81. {
  82. }
  83. public XmlTextReader (Stream xmlFragment, XmlNodeType fragType, XmlParserContext context)
  84. : this (String.Empty, new StreamReader (xmlFragment), fragType, context)
  85. {
  86. }
  87. public XmlTextReader (string url, Stream input, XmlNameTable nt)
  88. : this (url, new StreamReader (input), nt)
  89. {
  90. }
  91. public XmlTextReader (string url, TextReader input, XmlNameTable nt)
  92. : this (url, input, XmlNodeType.Document, new XmlParserContext (nt, new XmlNamespaceManager (nt), null, XmlSpace.None))
  93. {
  94. }
  95. [MonoTODO("TODO as same as private XmlTextReader(TextReader, XmlNodeType, XmlParserContext)")]
  96. public XmlTextReader (string xmlFragment, XmlNodeType fragType, XmlParserContext context)
  97. : this (String.Empty, new StringReader (xmlFragment), fragType, context)
  98. {
  99. }
  100. // TODO still remains as described at head of this file,
  101. // but it might not be TODO of the constructors...
  102. XmlTextReader (string url, TextReader fragment, XmlNodeType fragType, XmlParserContext context)
  103. {
  104. this.SetReaderContext(url, context);
  105. this.SetReaderFragment(fragment, fragType);
  106. }
  107. #endregion
  108. #region Properties
  109. public override int AttributeCount
  110. {
  111. get { return attributes.Count; }
  112. }
  113. public override string BaseURI
  114. {
  115. get { return parserContext.BaseURI; }
  116. }
  117. public override int Depth
  118. {
  119. get {
  120. return elementDepth;
  121. }
  122. }
  123. public Encoding Encoding
  124. {
  125. get { return parserContext.Encoding; }
  126. }
  127. public override bool EOF
  128. {
  129. get
  130. {
  131. return
  132. readState == ReadState.EndOfFile ||
  133. readState == ReadState.Closed;
  134. }
  135. }
  136. public override bool HasValue
  137. {
  138. get { return value != String.Empty; }
  139. }
  140. public override bool IsDefault
  141. {
  142. get
  143. {
  144. // XmlTextReader does not expand default attributes.
  145. return false;
  146. }
  147. }
  148. public override bool IsEmptyElement
  149. {
  150. get { return isEmptyElement; }
  151. }
  152. public override string this [int i]
  153. {
  154. get { return GetAttribute (i); }
  155. }
  156. public override string this [string name]
  157. {
  158. get { return GetAttribute (name); }
  159. }
  160. public override string this [string localName, string namespaceName]
  161. {
  162. get { return GetAttribute (localName, namespaceName); }
  163. }
  164. public int LineNumber
  165. {
  166. get { return line; }
  167. }
  168. public int LinePosition
  169. {
  170. get { return column; }
  171. }
  172. public override string LocalName
  173. {
  174. get { return localName; }
  175. }
  176. public override string Name
  177. {
  178. get { return name; }
  179. }
  180. [MonoTODO]
  181. public bool Namespaces
  182. {
  183. get { throw new NotImplementedException (); }
  184. set { throw new NotImplementedException (); }
  185. }
  186. public override string NamespaceURI
  187. {
  188. get { return namespaceURI; }
  189. }
  190. public override XmlNameTable NameTable
  191. {
  192. get { return parserContext.NameTable; }
  193. }
  194. public override XmlNodeType NodeType
  195. {
  196. get { return nodeType; }
  197. }
  198. [MonoTODO]
  199. public bool Normalization
  200. {
  201. get { throw new NotImplementedException (); }
  202. set { throw new NotImplementedException (); }
  203. }
  204. public override string Prefix
  205. {
  206. get { return prefix; }
  207. }
  208. public override char QuoteChar
  209. {
  210. get {
  211. // value string holds attribute quotation char.
  212. if (NodeType == XmlNodeType.Attribute)
  213. return value [0];
  214. else
  215. return '"';
  216. }
  217. }
  218. public override ReadState ReadState
  219. {
  220. get { return readState; }
  221. }
  222. public override string Value
  223. {
  224. get {
  225. if(NodeType == XmlNodeType.Attribute)
  226. return ResolveAttributeValue(value);
  227. else
  228. return value;
  229. }
  230. }
  231. public WhitespaceHandling WhitespaceHandling
  232. {
  233. get { return whitespaceHandling; }
  234. set { whitespaceHandling = value; }
  235. }
  236. [MonoTODO]
  237. public override string XmlLang
  238. {
  239. get { throw new NotImplementedException (); }
  240. }
  241. [MonoTODO]
  242. public XmlResolver XmlResolver
  243. {
  244. set { throw new NotImplementedException (); }
  245. }
  246. [MonoTODO]
  247. public override XmlSpace XmlSpace
  248. {
  249. get { throw new NotImplementedException (); }
  250. }
  251. #endregion
  252. #region Methods
  253. [MonoTODO]
  254. public override void Close ()
  255. {
  256. readState = ReadState.Closed;
  257. }
  258. [MonoTODO]
  259. public override string GetAttribute (int i)
  260. {
  261. if (i > attributes.Count)
  262. throw new ArgumentOutOfRangeException ("i is smaller than AttributeCount");
  263. else
  264. return ResolveAttributeValue (attributes [orderedAttributes [i]] as string);
  265. }
  266. public override string GetAttribute (string name)
  267. {
  268. return attributes.ContainsKey (name) ?
  269. ResolveAttributeValue (attributes [name] as string) : String.Empty;
  270. }
  271. public override string GetAttribute (string localName, string namespaceURI)
  272. {
  273. foreach (DictionaryEntry entry in attributes)
  274. {
  275. string thisName = entry.Key as string;
  276. int indexOfColon = thisName.IndexOf (':');
  277. if (indexOfColon != -1) {
  278. string thisLocalName = thisName.Substring (indexOfColon + 1);
  279. if (localName == thisLocalName) {
  280. string thisPrefix = thisName.Substring (0, indexOfColon);
  281. string thisNamespaceURI = LookupNamespace (thisPrefix);
  282. if (namespaceURI == thisNamespaceURI)
  283. return attributes.ContainsKey (thisName) ?
  284. ResolveAttributeValue (attributes [thisName] as string) : String.Empty;
  285. }
  286. } else if (localName == "xmlns" && namespaceURI == "http://www.w3.org/2000/xmlns/" && thisName == "xmlns")
  287. return attributes.ContainsKey (thisName) ?
  288. ResolveAttributeValue (attributes [thisName] as string) : String.Empty;
  289. }
  290. return String.Empty;
  291. }
  292. [MonoTODO]
  293. public TextReader GetRemainder ()
  294. {
  295. throw new NotImplementedException ();
  296. }
  297. [MonoTODO]
  298. bool IXmlLineInfo.HasLineInfo ()
  299. {
  300. return false;
  301. }
  302. public override string LookupNamespace (string prefix)
  303. {
  304. return parserContext.NamespaceManager.LookupNamespace (prefix);
  305. }
  306. public override void MoveToAttribute (int i)
  307. {
  308. MoveToElement ();
  309. if (attributes == null || orderedAttributes.Count < i || i < 0)
  310. throw new ArgumentOutOfRangeException ("attribute index out of range.");
  311. string name = orderedAttributes [i] as string;
  312. string value = attributes [name] as string;
  313. SetProperties (
  314. XmlNodeType.Attribute, // nodeType
  315. name, // name
  316. false, // isEmptyElement
  317. value, // value
  318. false // clearAttributes
  319. );
  320. }
  321. public override bool MoveToAttribute (string name)
  322. {
  323. MoveToElement ();
  324. bool match = false;
  325. if (attributes == null)
  326. return false;
  327. if (orderedAttributesEnumerator == null) {
  328. SaveProperties ();
  329. orderedAttributesEnumerator = orderedAttributes.GetEnumerator ();
  330. }
  331. while (orderedAttributesEnumerator.MoveNext ()) {
  332. if(name == orderedAttributesEnumerator.Current as string) {
  333. match = true;
  334. break;
  335. }
  336. }
  337. if (match) {
  338. string value = attributes [name] as string;
  339. SetProperties (
  340. XmlNodeType.Attribute, // nodeType
  341. name, // name
  342. false, // isEmptyElement
  343. value, // value
  344. false // clearAttributes
  345. );
  346. }
  347. return match;
  348. }
  349. [MonoTODO]
  350. public override bool MoveToAttribute (string localName, string namespaceName)
  351. {
  352. throw new NotImplementedException ();
  353. }
  354. public override bool MoveToElement ()
  355. {
  356. if (orderedAttributesEnumerator != null) {
  357. orderedAttributesEnumerator = null;
  358. RestoreProperties ();
  359. return true;
  360. }
  361. return false;
  362. }
  363. public override bool MoveToFirstAttribute ()
  364. {
  365. MoveToElement ();
  366. return MoveToNextAttribute ();
  367. }
  368. public override bool MoveToNextAttribute ()
  369. {
  370. if (attributes == null)
  371. return false;
  372. if (orderedAttributesEnumerator == null) {
  373. SaveProperties ();
  374. orderedAttributesEnumerator = orderedAttributes.GetEnumerator ();
  375. }
  376. if (orderedAttributesEnumerator.MoveNext ()) {
  377. string name = orderedAttributesEnumerator.Current as string;
  378. string value = attributes [name] as string;
  379. SetProperties (
  380. XmlNodeType.Attribute, // nodeType
  381. name, // name
  382. false, // isEmptyElement
  383. value, // value
  384. false // clearAttributes
  385. );
  386. return true;
  387. }
  388. return false;
  389. }
  390. public override bool Read ()
  391. {
  392. bool more = false;
  393. readState = ReadState.Interactive;
  394. more = ReadContent ();
  395. return more;
  396. }
  397. [MonoTODO("This method should consider entity references")]
  398. public override bool ReadAttributeValue ()
  399. {
  400. // reading attribute value phase now stopped
  401. if(attributeStringCurrentPosition < 0 ||
  402. attributeString.Length < attributeStringCurrentPosition) {
  403. attributeStringCurrentPosition = 0;
  404. attributeString = String.Empty;
  405. return false;
  406. }
  407. // If not started, then initialize attributeString when parsing is at start.
  408. if(attributeStringCurrentPosition == 0)
  409. attributeString =
  410. value.Substring (1, value.Length - 2);
  411. bool returnEntity = false;
  412. value = String.Empty;
  413. int nextPosition = attributeString.IndexOf ('&',
  414. attributeStringCurrentPosition);
  415. // if attribute string starts from '&' then it may be (unparsable) entity reference.
  416. if(nextPosition == 0) {
  417. string parsed = ReadAttributeValueEntityReference ();
  418. if(parsed == null) {
  419. // return entity (It is only this case to return entity reference.)
  420. int endEntityPosition = attributeString.IndexOf (';',
  421. attributeStringCurrentPosition);
  422. SetProperties (XmlNodeType.EntityReference,
  423. attributeString.Substring (attributeStringCurrentPosition + 1,
  424. endEntityPosition - attributeStringCurrentPosition - 1),
  425. false,
  426. String.Empty,
  427. false);
  428. attributeStringCurrentPosition = endEntityPosition + 1;
  429. return true;
  430. }
  431. else
  432. value += parsed;
  433. }
  434. // Other case always set text node.
  435. while(!returnEntity) {
  436. nextPosition = attributeString.IndexOf ('&', attributeStringCurrentPosition);
  437. if(nextPosition < 0) {
  438. // Reached to the end of value string.
  439. value += attributeString.Substring (attributeStringCurrentPosition);
  440. attributeStringCurrentPosition = -1;
  441. break;
  442. } else if(nextPosition == attributeStringCurrentPosition) {
  443. string parsed = ReadAttributeValueEntityReference ();
  444. if(parsed != null)
  445. value += parsed;
  446. else {
  447. // Found that an entity reference starts from this point.
  448. // Then once stop to parse attribute value and then return text.
  449. value += attributeString.Substring (attributeStringCurrentPosition,
  450. nextPosition - attributeStringCurrentPosition);
  451. break;
  452. }
  453. } else {
  454. value += attributeString.Substring (attributeStringCurrentPosition,
  455. nextPosition - attributeStringCurrentPosition);
  456. attributeStringCurrentPosition = nextPosition;
  457. continue;
  458. }
  459. }
  460. SetProperties(XmlNodeType.Text,
  461. "#text",
  462. false,
  463. value,
  464. false);
  465. return true;
  466. }
  467. [MonoTODO]
  468. public int ReadBase64 (byte [] buffer, int offset, int length)
  469. {
  470. throw new NotImplementedException ();
  471. }
  472. [MonoTODO]
  473. public int ReadBinHex (byte [] buffer, int offset, int length)
  474. {
  475. throw new NotImplementedException ();
  476. }
  477. [MonoTODO]
  478. public int ReadChars (char [] buffer, int offset, int length)
  479. {
  480. throw new NotImplementedException ();
  481. }
  482. [MonoTODO]
  483. public override string ReadInnerXml ()
  484. {
  485. // Still need a Well Formedness check.
  486. // Will wait for Validating reader ;-)
  487. if (NodeType == XmlNodeType.Attribute) {
  488. return Value;
  489. } else {
  490. saveToXmlBuffer = true;
  491. string startname = this.Name;
  492. string endname = string.Empty;
  493. readState = ReadState.Interactive;
  494. while (startname != endname) {
  495. ReadContent ();
  496. endname = this.Name;
  497. }
  498. xmlBuffer.Replace (currentTag.ToString (), "");
  499. saveToXmlBuffer = false;
  500. string InnerXml = xmlBuffer.ToString ();
  501. xmlBuffer.Length = 0;
  502. return InnerXml;
  503. }
  504. }
  505. [MonoTODO]
  506. public override string ReadOuterXml ()
  507. {
  508. if (NodeType == XmlNodeType.Attribute) {
  509. return Name + "=\"" + Value.Replace ("\"", "&quot;") + "\"";
  510. } else {
  511. saveToXmlBuffer = true;
  512. xmlBuffer.Append (currentTag.ToString ());
  513. int startDepth = Depth;
  514. readState = ReadState.Interactive;
  515. do {
  516. ReadContent ();
  517. } while (Depth > startDepth);
  518. saveToXmlBuffer = false;
  519. string OuterXml = xmlBuffer.ToString ();
  520. xmlBuffer.Length = 0;
  521. return OuterXml;
  522. }
  523. }
  524. [MonoTODO]
  525. public override string ReadString ()
  526. {
  527. throw new NotImplementedException ();
  528. }
  529. [MonoTODO]
  530. public void ResetState ()
  531. {
  532. throw new NotImplementedException ();
  533. }
  534. public override void ResolveEntity ()
  535. {
  536. // XmlTextReaders don't resolve entities.
  537. throw new InvalidOperationException ("XmlTextReader cannot resolve external entities.");
  538. }
  539. #endregion
  540. #region Internals
  541. internal string publicId;
  542. internal string systemId;
  543. internal void SetReaderContext (string url, XmlParserContext context)
  544. {
  545. parserContext = context;
  546. parserContext.BaseURI = url;
  547. Init ();
  548. }
  549. internal void SetReaderFragment(TextReader fragment, XmlNodeType fragType)
  550. {
  551. this.reader = fragment;
  552. StreamReader sr = fragment as StreamReader;
  553. if (sr != null)
  554. can_seek = sr.BaseStream.CanSeek;
  555. else
  556. can_seek = fragment != null && fragment.Peek () != -1;
  557. if (fragType == XmlNodeType.Attribute)
  558. value = "''";
  559. /* for future use
  560. switch(fragType)
  561. {
  562. case XmlNodeType.Attribute: // attribute content
  563. parserContext.InputState = XmlParserInputState.AttributeValue;
  564. break;
  565. case XmlNodeType.DocumentFragment: // element content
  566. parserContext.InputState = XmlParserInputState.Content;
  567. break;
  568. case XmlNodeType.Element: // one element
  569. parserContext.InputState = XmlParserInputState.StartTag;
  570. break;
  571. case XmlNodeType.Document: // document content
  572. parserContext.InputState = XmlParserInputState.Start;
  573. break;
  574. default:
  575. throw new InvalidOperationException("setting this xml node type not allowed.");
  576. }
  577. */
  578. }
  579. #endregion
  580. #region Privates
  581. private XmlParserContext parserContext;
  582. private TextReader reader;
  583. private ReadState readState;
  584. private int depth;
  585. private int elementDepth;
  586. private bool depthDown;
  587. private bool popScope;
  588. private XmlNodeType nodeType;
  589. private string name;
  590. private string prefix;
  591. private string localName;
  592. private string namespaceURI;
  593. private bool isEmptyElement;
  594. private string value;
  595. private XmlNodeType saveNodeType;
  596. private string saveName;
  597. private string savePrefix;
  598. private string saveLocalName;
  599. private string saveNamespaceURI;
  600. private bool saveIsEmptyElement;
  601. private Hashtable attributes;
  602. private ArrayList orderedAttributes;
  603. private IEnumerator orderedAttributesEnumerator;
  604. private bool returnEntityReference;
  605. private string entityReferenceName;
  606. private char [] nameBuffer;
  607. private int nameLength;
  608. private int nameCapacity;
  609. private const int initialNameCapacity = 256;
  610. private char [] valueBuffer;
  611. private int valueLength;
  612. private int valueCapacity;
  613. private const int initialValueCapacity = 8192;
  614. private StringBuilder xmlBuffer; // This is for Read(Inner|Outer)Xml
  615. private StringBuilder currentTag; // A buffer for ReadContent for ReadOuterXml
  616. private bool saveToXmlBuffer;
  617. private int line = 1;
  618. private int column = 1;
  619. private bool has_peek;
  620. private bool can_seek;
  621. private int peek_char;
  622. private string attributeString = String.Empty;
  623. private int attributeStringCurrentPosition;
  624. private void Init ()
  625. {
  626. readState = ReadState.Initial;
  627. depth = 0;
  628. depthDown = false;
  629. popScope = false;
  630. nodeType = XmlNodeType.None;
  631. name = String.Empty;
  632. prefix = String.Empty;
  633. localName = string.Empty;
  634. isEmptyElement = false;
  635. value = String.Empty;
  636. attributes = new Hashtable ();
  637. orderedAttributes = new ArrayList ();
  638. orderedAttributesEnumerator = null;
  639. returnEntityReference = false;
  640. entityReferenceName = String.Empty;
  641. nameBuffer = new char [initialNameCapacity];
  642. nameLength = 0;
  643. nameCapacity = initialNameCapacity;
  644. valueBuffer = new char [initialValueCapacity];
  645. valueLength = 0;
  646. valueCapacity = initialValueCapacity;
  647. xmlBuffer = new StringBuilder ();
  648. currentTag = new StringBuilder ();
  649. }
  650. // Use this method rather than setting the properties
  651. // directly so that all the necessary properties can
  652. // be changed in harmony with each other. Maybe the
  653. // fields should be in a seperate class to help enforce
  654. // this.
  655. private void SetProperties (
  656. XmlNodeType nodeType,
  657. string name,
  658. bool isEmptyElement,
  659. string value,
  660. bool clearAttributes)
  661. {
  662. this.nodeType = nodeType;
  663. this.name = name;
  664. this.isEmptyElement = isEmptyElement;
  665. this.value = value;
  666. this.elementDepth = depth;
  667. if (clearAttributes)
  668. ClearAttributes ();
  669. int indexOfColon = name.IndexOf (':');
  670. if (indexOfColon == -1) {
  671. prefix = String.Empty;
  672. localName = name;
  673. } else {
  674. prefix = name.Substring (0, indexOfColon);
  675. localName = name.Substring (indexOfColon + 1);
  676. }
  677. namespaceURI = LookupNamespace (prefix);
  678. }
  679. private void SaveProperties ()
  680. {
  681. saveNodeType = nodeType;
  682. saveName = name;
  683. savePrefix = prefix;
  684. saveLocalName = localName;
  685. saveNamespaceURI = namespaceURI;
  686. saveIsEmptyElement = isEmptyElement;
  687. // An element's value is always String.Empty.
  688. }
  689. private void RestoreProperties ()
  690. {
  691. nodeType = saveNodeType;
  692. name = saveName;
  693. prefix = savePrefix;
  694. localName = saveLocalName;
  695. namespaceURI = saveNamespaceURI;
  696. isEmptyElement = saveIsEmptyElement;
  697. value = String.Empty;
  698. }
  699. private void AddAttribute (string name, string value)
  700. {
  701. attributes.Add (name, value);
  702. orderedAttributes.Add (name);
  703. }
  704. private void ClearAttributes ()
  705. {
  706. if (attributes.Count > 0) {
  707. attributes.Clear ();
  708. orderedAttributes.Clear ();
  709. }
  710. orderedAttributesEnumerator = null;
  711. }
  712. private int PeekChar ()
  713. {
  714. if (can_seek)
  715. return reader.Peek ();
  716. if (has_peek)
  717. return peek_char;
  718. peek_char = reader.Read ();
  719. has_peek = true;
  720. return peek_char;
  721. }
  722. private int ReadChar ()
  723. {
  724. int ch;
  725. if (has_peek) {
  726. ch = peek_char;
  727. has_peek = false;
  728. } else {
  729. ch = reader.Read ();
  730. }
  731. if (ch == '\n') {
  732. line++;
  733. column = 1;
  734. } else {
  735. column++;
  736. }
  737. if (saveToXmlBuffer) {
  738. xmlBuffer.Append ((char) ch);
  739. }
  740. currentTag.Append ((char) ch);
  741. return ch;
  742. }
  743. // This should really keep track of some state so
  744. // that it's not possible to have more than one document
  745. // element or text outside of the document element.
  746. private bool ReadContent ()
  747. {
  748. currentTag.Length = 0;
  749. if (popScope) {
  750. parserContext.NamespaceManager.PopScope ();
  751. popScope = false;
  752. }
  753. if (returnEntityReference) {
  754. SetEntityReferenceProperties ();
  755. } else {
  756. switch (PeekChar ())
  757. {
  758. case '<':
  759. ReadChar ();
  760. ReadTag ();
  761. break;
  762. case '\r':
  763. if (whitespaceHandling == WhitespaceHandling.All ||
  764. whitespaceHandling == WhitespaceHandling.Significant)
  765. return ReadWhitespace ();
  766. ReadChar ();
  767. return ReadContent ();
  768. case '\n':
  769. if (whitespaceHandling == WhitespaceHandling.All ||
  770. whitespaceHandling == WhitespaceHandling.Significant)
  771. return ReadWhitespace ();
  772. ReadChar ();
  773. return ReadContent ();
  774. case ' ':
  775. if (whitespaceHandling == WhitespaceHandling.All ||
  776. whitespaceHandling == WhitespaceHandling.Significant)
  777. return ReadWhitespace ();
  778. SkipWhitespace ();
  779. return ReadContent ();
  780. case -1:
  781. readState = ReadState.EndOfFile;
  782. SetProperties (
  783. XmlNodeType.None, // nodeType
  784. String.Empty, // name
  785. false, // isEmptyElement
  786. String.Empty, // value
  787. true // clearAttributes
  788. );
  789. break;
  790. default:
  791. ReadText (true);
  792. break;
  793. }
  794. }
  795. return this.ReadState != ReadState.EndOfFile;
  796. }
  797. private void SetEntityReferenceProperties ()
  798. {
  799. SetProperties (
  800. XmlNodeType.EntityReference, // nodeType
  801. entityReferenceName, // name
  802. false, // isEmptyElement
  803. String.Empty, // value
  804. true // clearAttributes
  805. );
  806. returnEntityReference = false;
  807. entityReferenceName = String.Empty;
  808. }
  809. // The leading '<' has already been consumed.
  810. private void ReadTag ()
  811. {
  812. switch (PeekChar ())
  813. {
  814. case '/':
  815. ReadChar ();
  816. ReadEndTag ();
  817. break;
  818. case '?':
  819. ReadChar ();
  820. ReadProcessingInstruction ();
  821. break;
  822. case '!':
  823. ReadChar ();
  824. ReadDeclaration ();
  825. break;
  826. default:
  827. ReadStartTag ();
  828. break;
  829. }
  830. }
  831. // The leading '<' has already been consumed.
  832. private void ReadStartTag ()
  833. {
  834. parserContext.NamespaceManager.PushScope ();
  835. string name = ReadName ();
  836. SkipWhitespace ();
  837. bool isEmptyElement = false;
  838. ClearAttributes ();
  839. if (XmlChar.IsFirstNameChar (PeekChar ()))
  840. ReadAttributes ();
  841. if (PeekChar () == '/') {
  842. ReadChar ();
  843. isEmptyElement = true;
  844. depthDown = true;
  845. popScope = true;
  846. }
  847. Expect ('>');
  848. SetProperties (
  849. XmlNodeType.Element, // nodeType
  850. name, // name
  851. isEmptyElement, // isEmptyElement
  852. String.Empty, // value
  853. false // clearAttributes
  854. );
  855. if (!depthDown)
  856. ++depth;
  857. else
  858. depthDown = false;
  859. }
  860. // The reader is positioned on the first character
  861. // of the element's name.
  862. private void ReadEndTag ()
  863. {
  864. string name = ReadName ();
  865. SkipWhitespace ();
  866. Expect ('>');
  867. --depth;
  868. SetProperties (
  869. XmlNodeType.EndElement, // nodeType
  870. name, // name
  871. false, // isEmptyElement
  872. String.Empty, // value
  873. true // clearAttributes
  874. );
  875. popScope = true;
  876. }
  877. private void AppendNameChar (int ch)
  878. {
  879. CheckNameCapacity ();
  880. nameBuffer [nameLength++] = (char)ch;
  881. }
  882. private void CheckNameCapacity ()
  883. {
  884. if (nameLength == nameCapacity) {
  885. nameCapacity = nameCapacity * 2;
  886. char [] oldNameBuffer = nameBuffer;
  887. nameBuffer = new char [nameCapacity];
  888. Array.Copy (oldNameBuffer, nameBuffer, nameLength);
  889. }
  890. }
  891. private string CreateNameString ()
  892. {
  893. return new String (nameBuffer, 0, nameLength);
  894. }
  895. private void AppendValueChar (int ch)
  896. {
  897. CheckValueCapacity ();
  898. valueBuffer [valueLength++] = (char)ch;
  899. }
  900. private void CheckValueCapacity ()
  901. {
  902. if (valueLength == valueCapacity) {
  903. valueCapacity = valueCapacity * 2;
  904. char [] oldValueBuffer = valueBuffer;
  905. valueBuffer = new char [valueCapacity];
  906. Array.Copy (oldValueBuffer, valueBuffer, valueLength);
  907. }
  908. }
  909. private string CreateValueString ()
  910. {
  911. return new String (valueBuffer, 0, valueLength);
  912. }
  913. // The reader is positioned on the first character
  914. // of the text.
  915. private void ReadText (bool cleanValue)
  916. {
  917. if (cleanValue)
  918. valueLength = 0;
  919. int ch = PeekChar ();
  920. while (ch != '<' && ch != -1) {
  921. if (ch == '&') {
  922. ReadChar ();
  923. if (ReadReference (false))
  924. break;
  925. } else
  926. AppendValueChar (ReadChar ());
  927. ch = PeekChar ();
  928. }
  929. if (returnEntityReference && valueLength == 0) {
  930. SetEntityReferenceProperties ();
  931. } else {
  932. SetProperties (
  933. XmlNodeType.Text, // nodeType
  934. String.Empty, // name
  935. false, // isEmptyElement
  936. CreateValueString (), // value
  937. true // clearAttributes
  938. );
  939. }
  940. }
  941. // The leading '&' has already been consumed.
  942. // Returns true if the entity reference isn't a simple
  943. // character reference or one of the predefined entities.
  944. // This allows the ReadText method to break so that the
  945. // next call to Read will return the EntityReference node.
  946. private bool ReadReference (bool ignoreEntityReferences)
  947. {
  948. if (PeekChar () == '#') {
  949. ReadChar ();
  950. ReadCharacterReference ();
  951. } else
  952. ReadEntityReference (ignoreEntityReferences);
  953. return returnEntityReference;
  954. }
  955. private void ReadCharacterReference ()
  956. {
  957. int value = 0;
  958. if (PeekChar () == 'x') {
  959. ReadChar ();
  960. while (PeekChar () != ';' && PeekChar () != -1) {
  961. int ch = ReadChar ();
  962. if (ch >= '0' && ch <= '9')
  963. value = (value << 4) + ch - '0';
  964. else if (ch >= 'A' && ch <= 'F')
  965. value = (value << 4) + ch - 'A' + 10;
  966. else if (ch >= 'a' && ch <= 'f')
  967. value = (value << 4) + ch - 'a' + 10;
  968. else
  969. throw new XmlException (
  970. String.Format (
  971. "invalid hexadecimal digit: {0} (#x{1:X})",
  972. (char)ch,
  973. ch));
  974. }
  975. } else {
  976. while (PeekChar () != ';' && PeekChar () != -1) {
  977. int ch = ReadChar ();
  978. if (ch >= '0' && ch <= '9')
  979. value = value * 10 + ch - '0';
  980. else
  981. throw new XmlException (
  982. String.Format (
  983. "invalid decimal digit: {0} (#x{1:X})",
  984. (char)ch,
  985. ch));
  986. }
  987. }
  988. ReadChar (); // ';'
  989. AppendValueChar (value);
  990. }
  991. private void ReadEntityReference (bool ignoreEntityReferences)
  992. {
  993. nameLength = 0;
  994. int ch = PeekChar ();
  995. while (ch != ';' && ch != -1) {
  996. AppendNameChar (ReadChar ());
  997. ch = PeekChar ();
  998. }
  999. Expect (';');
  1000. string name = CreateNameString ();
  1001. switch (name)
  1002. {
  1003. case "lt":
  1004. AppendValueChar ('<');
  1005. break;
  1006. case "gt":
  1007. AppendValueChar ('>');
  1008. break;
  1009. case "amp":
  1010. AppendValueChar ('&');
  1011. break;
  1012. case "apos":
  1013. AppendValueChar ('\'');
  1014. break;
  1015. case "quot":
  1016. AppendValueChar ('"');
  1017. break;
  1018. default:
  1019. if (ignoreEntityReferences) {
  1020. AppendValueChar ('&');
  1021. foreach (char ch2 in name) {
  1022. AppendValueChar (ch2);
  1023. }
  1024. AppendValueChar (';');
  1025. } else {
  1026. returnEntityReference = true;
  1027. entityReferenceName = name;
  1028. }
  1029. break;
  1030. }
  1031. }
  1032. // The reader is positioned on the first character of
  1033. // the attribute name.
  1034. private void ReadAttributes ()
  1035. {
  1036. do {
  1037. string name = ReadName ();
  1038. SkipWhitespace ();
  1039. Expect ('=');
  1040. SkipWhitespace ();
  1041. string value = ReadAttribute ();
  1042. SkipWhitespace ();
  1043. if (name == "xmlns")
  1044. parserContext.NamespaceManager.AddNamespace (String.Empty, ResolveAttributeValue (value));
  1045. else if (name.StartsWith ("xmlns:"))
  1046. parserContext.NamespaceManager.AddNamespace (name.Substring (6), ResolveAttributeValue (value));
  1047. AddAttribute (name, value);
  1048. } while (PeekChar () != '/' && PeekChar () != '>' && PeekChar () != -1);
  1049. }
  1050. // The reader is positioned on the quote character.
  1051. private string ReadAttribute ()
  1052. {
  1053. valueLength = 0;
  1054. int quoteChar = ReadChar ();
  1055. if (quoteChar != '\'' && quoteChar != '\"')
  1056. throw new XmlException ("an attribute value was not quoted");
  1057. // this keeps quote char to get QuoteChar property correctly.
  1058. AppendValueChar (quoteChar);
  1059. while (PeekChar () != quoteChar) {
  1060. int ch = ReadChar ();
  1061. switch (ch)
  1062. {
  1063. case '<':
  1064. throw new XmlException ("attribute values cannot contain '<'");
  1065. // expansion of entity now should be done at ResolveAttributeValue() method
  1066. // case '&':
  1067. // ReadReference (true);
  1068. // break;
  1069. case -1:
  1070. throw new XmlException ("unexpected end of file in an attribute value");
  1071. default:
  1072. AppendValueChar (ch);
  1073. break;
  1074. }
  1075. }
  1076. ReadChar (); // quoteChar
  1077. AppendValueChar (quoteChar);
  1078. return CreateValueString ();
  1079. }
  1080. // The reader is positioned on the first character
  1081. // of the target.
  1082. //
  1083. // Now it also reads XmlDeclaration, this method name became improper...
  1084. private void ReadProcessingInstruction ()
  1085. {
  1086. string target = ReadName ();
  1087. SkipWhitespace ();
  1088. valueLength = 0;
  1089. while (PeekChar () != -1) {
  1090. int ch = ReadChar ();
  1091. if (ch == '?' && PeekChar () == '>') {
  1092. ReadChar ();
  1093. break;
  1094. }
  1095. AppendValueChar ((char)ch);
  1096. }
  1097. /* for future use
  1098. if(target == "xml") && parserContext.InputState != XmlParserInputState.Start)
  1099. throw new XmlException("Xml declaration is not allowed here.");
  1100. else {
  1101. parserContext.InputState = XmlParserInputState.DTD; //for future use
  1102. }
  1103. */
  1104. SetProperties (
  1105. target == "xml" ?
  1106. XmlNodeType.XmlDeclaration :
  1107. XmlNodeType.ProcessingInstruction, // nodeType
  1108. target, // name
  1109. false, // isEmptyElement
  1110. CreateValueString (), // value
  1111. true // clearAttributes
  1112. );
  1113. }
  1114. // The reader is positioned on the first character after
  1115. // the leading '<!'.
  1116. private void ReadDeclaration ()
  1117. {
  1118. int ch = PeekChar ();
  1119. switch (ch)
  1120. {
  1121. case '-':
  1122. Expect ("--");
  1123. ReadComment ();
  1124. break;
  1125. case '[':
  1126. ReadChar ();
  1127. Expect ("CDATA[");
  1128. ReadCDATA ();
  1129. break;
  1130. case 'D':
  1131. Expect ("DOCTYPE");
  1132. ReadDoctypeDecl ();
  1133. break;
  1134. }
  1135. }
  1136. // The reader is positioned on the first character after
  1137. // the leading '<!--'.
  1138. private void ReadComment ()
  1139. {
  1140. valueLength = 0;
  1141. while (PeekChar () != -1) {
  1142. int ch = ReadChar ();
  1143. if (ch == '-' && PeekChar () == '-') {
  1144. ReadChar ();
  1145. if (PeekChar () != '>')
  1146. throw new XmlException ("comments cannot contain '--'");
  1147. ReadChar ();
  1148. break;
  1149. }
  1150. AppendValueChar ((char)ch);
  1151. }
  1152. SetProperties (
  1153. XmlNodeType.Comment, // nodeType
  1154. String.Empty, // name
  1155. false, // isEmptyElement
  1156. CreateValueString (), // value
  1157. true // clearAttributes
  1158. );
  1159. }
  1160. // The reader is positioned on the first character after
  1161. // the leading '<![CDATA['.
  1162. private void ReadCDATA ()
  1163. {
  1164. valueLength = 0;
  1165. while (PeekChar () != -1) {
  1166. int ch = ReadChar ();
  1167. if (ch == ']' && PeekChar () == ']') {
  1168. ch = ReadChar (); // ']'
  1169. if (PeekChar () == '>') {
  1170. ReadChar (); // '>'
  1171. break;
  1172. } else {
  1173. AppendValueChar (']');
  1174. AppendValueChar (']');
  1175. ch = ReadChar ();
  1176. }
  1177. }
  1178. AppendValueChar ((char)ch);
  1179. }
  1180. SetProperties (
  1181. XmlNodeType.CDATA, // nodeType
  1182. String.Empty, // name
  1183. false, // isEmptyElement
  1184. CreateValueString (), // value
  1185. true // clearAttributes
  1186. );
  1187. }
  1188. // The reader is positioned on the first character after
  1189. // the leading '<!DOCTYPE'.
  1190. private void ReadDoctypeDecl ()
  1191. {
  1192. string doctypeName = null;
  1193. string publicId = String.Empty;
  1194. string systemId = String.Empty;
  1195. SkipWhitespace ();
  1196. doctypeName = ReadName ();
  1197. SkipWhitespace ();
  1198. xmlBuffer.Length = 0;
  1199. switch(PeekChar ())
  1200. {
  1201. case 'S':
  1202. systemId = ReadSystemLiteral (true);
  1203. break;
  1204. case 'P':
  1205. publicId = ReadPubidLiteral ();
  1206. SkipWhitespace ();
  1207. systemId = ReadSystemLiteral (false);
  1208. break;
  1209. }
  1210. SkipWhitespace ();
  1211. if(PeekChar () == '[')
  1212. {
  1213. // read markupdecl etc. or end of decl
  1214. ReadChar ();
  1215. xmlBuffer.Length = 0;
  1216. saveToXmlBuffer = true;
  1217. do {
  1218. ReadDTDInternalSubset ();
  1219. } while(nodeType != XmlNodeType.None);
  1220. xmlBuffer.Remove (xmlBuffer.Length - 1, 1); // cut off ']'
  1221. saveToXmlBuffer = false;
  1222. }
  1223. // end of DOCTYPE decl.
  1224. SkipWhitespace ();
  1225. Expect ('>');
  1226. parserContext.InternalSubset = xmlBuffer.ToString ();
  1227. // set properties for <!DOCTYPE> node
  1228. SetProperties (
  1229. XmlNodeType.DocumentType, // nodeType
  1230. doctypeName, // name
  1231. false, // isEmptyElement
  1232. parserContext.InternalSubset, // value
  1233. true // clearAttributes
  1234. );
  1235. }
  1236. // Read any one of following:
  1237. // elementdecl, AttlistDecl, EntityDecl, NotationDecl,
  1238. // PI, Comment, Parameter Entity, or doctype termination char(']')
  1239. //
  1240. // returns a node of some nodeType or null, setting nodeType.
  1241. // (if None then ']' was found.)
  1242. private void ReadDTDInternalSubset()
  1243. {
  1244. SkipWhitespace ();
  1245. switch(ReadChar ())
  1246. {
  1247. case ']':
  1248. nodeType = XmlNodeType.None;
  1249. break;
  1250. case '%':
  1251. string peName = ReadName ();
  1252. Expect (';');
  1253. nodeType = XmlNodeType.EntityReference; // It's chating a bit;-)
  1254. break;
  1255. case '<':
  1256. switch(ReadChar ())
  1257. {
  1258. case '?':
  1259. ReadProcessingInstruction ();
  1260. break;
  1261. case '!':
  1262. switch(ReadChar ())
  1263. {
  1264. case '-':
  1265. Expect ('-');
  1266. ReadComment ();
  1267. break;
  1268. case 'E':
  1269. switch(ReadChar ())
  1270. {
  1271. case 'N':
  1272. Expect ("TITY");
  1273. ReadEntityDecl ();
  1274. break;
  1275. case 'L':
  1276. Expect ("EMENT");
  1277. ReadElementDecl ();
  1278. break;
  1279. default:
  1280. throw new XmlException ("Syntax Error after '<!E' (ELEMENT or ENTITY must be found)");
  1281. }
  1282. break;
  1283. case 'A':
  1284. Expect ("TTLIST");
  1285. ReadAttListDecl ();
  1286. break;
  1287. case 'N':
  1288. Expect ("OTATION");
  1289. ReadNotationDecl ();
  1290. break;
  1291. default:
  1292. throw new XmlException ("Syntax Error after '<!' characters.");
  1293. }
  1294. break;
  1295. default:
  1296. throw new XmlException ("Syntax Error after '<' character.");
  1297. }
  1298. break;
  1299. default:
  1300. throw new XmlException ("Syntax Error inside doctypedecl markup.");
  1301. }
  1302. }
  1303. // The reader is positioned on the head of the name.
  1304. private void ReadElementDecl()
  1305. {
  1306. while(ReadChar () != '>');
  1307. }
  1308. private void ReadEntityDecl()
  1309. {
  1310. while(ReadChar () != '>');
  1311. }
  1312. private void ReadAttListDecl()
  1313. {
  1314. while(ReadChar () != '>');
  1315. }
  1316. private void ReadNotationDecl()
  1317. {
  1318. while(ReadChar () != '>');
  1319. }
  1320. // The reader is positioned on the first 'S' of "SYSTEM".
  1321. private string ReadSystemLiteral (bool expectSYSTEM)
  1322. {
  1323. if(expectSYSTEM)
  1324. Expect ("SYSTEM");
  1325. SkipWhitespace ();
  1326. int quoteChar = ReadChar (); // apos or quot
  1327. xmlBuffer.Length = 0;
  1328. saveToXmlBuffer = true;
  1329. int c = 0;
  1330. while(c != quoteChar) {
  1331. c = ReadChar ();
  1332. if(c < 0) throw new XmlException ("Unexpected end of stream in ExternalID.");
  1333. }
  1334. saveToXmlBuffer = false;
  1335. xmlBuffer.Remove (xmlBuffer.Length-1, 1); // cut quoteChar
  1336. return xmlBuffer.ToString ();
  1337. }
  1338. private string ReadPubidLiteral()
  1339. {
  1340. Expect ("PUBLIC");
  1341. SkipWhitespace ();
  1342. int quoteChar = ReadChar ();
  1343. xmlBuffer.Length = 0;
  1344. saveToXmlBuffer = true;
  1345. int c = 0;
  1346. while(c != quoteChar)
  1347. {
  1348. c = ReadChar ();
  1349. if(c < 0) throw new XmlException ("Unexpected end of stream in ExternalID.");
  1350. if(c != quoteChar && !XmlChar.IsPubidChar (c))
  1351. throw new XmlException("character '" + (char)c + "' not allowed for PUBLIC ID");
  1352. }
  1353. ReadChar(); // skips quoteChar
  1354. xmlBuffer.Remove (xmlBuffer.Length-1, 1); // cut quoteChar
  1355. saveToXmlBuffer = false;
  1356. return xmlBuffer.ToString ();
  1357. }
  1358. // The reader is positioned on the first character
  1359. // of the name.
  1360. private string ReadName ()
  1361. {
  1362. if (!XmlChar.IsFirstNameChar (PeekChar ()))
  1363. throw new XmlException ("a name did not start with a legal character");
  1364. nameLength = 0;
  1365. AppendNameChar (ReadChar ());
  1366. while (XmlChar.IsNameChar (PeekChar ())) {
  1367. AppendNameChar (ReadChar ());
  1368. }
  1369. return CreateNameString ();
  1370. }
  1371. // Read the next character and compare it against the
  1372. // specified character.
  1373. private void Expect (int expected)
  1374. {
  1375. int ch = ReadChar ();
  1376. if (ch != expected) {
  1377. throw new XmlException (
  1378. String.Format (
  1379. "expected '{0}' ({1:X}) but found '{2}' ({3:X})",
  1380. (char)expected,
  1381. expected,
  1382. (char)ch,
  1383. ch));
  1384. }
  1385. }
  1386. private void Expect (string expected)
  1387. {
  1388. int len = expected.Length;
  1389. for(int i=0; i< len; i++)
  1390. Expect (expected[i]);
  1391. }
  1392. // Does not consume the first non-whitespace character.
  1393. private void SkipWhitespace ()
  1394. {
  1395. //FIXME: Should not skip if whitespaceHandling == WhiteSpaceHandling.None
  1396. while (XmlChar.IsWhitespace (PeekChar ()))
  1397. ReadChar ();
  1398. }
  1399. private bool ReadWhitespace ()
  1400. {
  1401. valueLength = 0;
  1402. int ch = PeekChar ();
  1403. do {
  1404. AppendValueChar (ReadChar ());
  1405. } while ((ch = PeekChar ()) != -1 && XmlChar.IsWhitespace (ch));
  1406. if (ch != -1 && ch != '<')
  1407. ReadText (false);
  1408. else
  1409. SetProperties (XmlNodeType.Whitespace,
  1410. String.Empty,
  1411. false,
  1412. CreateValueString (),
  1413. true);
  1414. return (PeekChar () != -1);
  1415. }
  1416. // read entity reference from attribute string and if parsable then return the value.
  1417. private string ReadAttributeValueEntityReference ()
  1418. {
  1419. int endEntityPosition = attributeString.IndexOf(';',
  1420. attributeStringCurrentPosition);
  1421. string entityName = attributeString.Substring (attributeStringCurrentPosition + 1,
  1422. endEntityPosition - attributeStringCurrentPosition - 1);
  1423. attributeStringCurrentPosition = endEntityPosition + 1;
  1424. if(entityName [0] == '#') {
  1425. char c;
  1426. // character entity
  1427. if(entityName [1] == 'x') {
  1428. // hexadecimal
  1429. c = (char) int.Parse ("0" + entityName.Substring (2),
  1430. System.Globalization.NumberStyles.HexNumber);
  1431. } else {
  1432. // decimal
  1433. c = (char) int.Parse (entityName.Substring (1));
  1434. }
  1435. return c.ToString();
  1436. }
  1437. else {
  1438. switch(entityName)
  1439. {
  1440. case "lt": return "<";
  1441. case "gt": return ">";
  1442. case "amp": return "&";
  1443. case "quot": return "\"";
  1444. case "apos": return "'";
  1445. default: return null;
  1446. }
  1447. }
  1448. }
  1449. private string ResolveAttributeValue (string unresolved)
  1450. {
  1451. if(unresolved == null) return null;
  1452. StringBuilder resolved = new StringBuilder();
  1453. int pos = 0;
  1454. // trim start/end edge of quotation character.
  1455. unresolved = unresolved.Substring (1, unresolved.Length - 2);
  1456. int next = unresolved.IndexOf ('&');
  1457. if(next < 0)
  1458. return unresolved;
  1459. while(next >= 0) {
  1460. if(pos < next)
  1461. resolved.Append (unresolved.Substring (pos, next - pos));// - 1);
  1462. int endPos = unresolved.IndexOf (';', next+1);
  1463. string entityName =
  1464. unresolved.Substring (next + 1, endPos - next - 1);
  1465. if(entityName [0] == '#') {
  1466. char c;
  1467. // character entity
  1468. if(entityName [1] == 'x') {
  1469. // hexadecimal
  1470. c = (char) int.Parse ("0" + entityName.Substring (2),
  1471. System.Globalization.NumberStyles.HexNumber);
  1472. } else {
  1473. // decimal
  1474. c = (char) int.Parse (entityName.Substring (1));
  1475. }
  1476. resolved.Append (c);
  1477. } else {
  1478. switch(entityName) {
  1479. case "lt": resolved.Append ("<"); break;
  1480. case "gt": resolved.Append (">"); break;
  1481. case "amp": resolved.Append ("&"); break;
  1482. case "quot": resolved.Append ("\""); break;
  1483. case "apos": resolved.Append ("'"); break;
  1484. // With respect to "Value", MS document is helpless
  1485. // and the implemention returns inconsistent value
  1486. // (e.g. XML: "&ent; &amp;ent;" ---> Value: "&ent; &ent;".)
  1487. default: resolved.Append ("&" + entityName + ";"); break;
  1488. }
  1489. }
  1490. pos = endPos + 1;
  1491. if(pos > unresolved.Length)
  1492. break;
  1493. next = unresolved.IndexOf('&', pos);
  1494. }
  1495. resolved.Append (unresolved.Substring(pos));
  1496. return resolved.ToString();
  1497. }
  1498. #endregion
  1499. }
  1500. }