XmlTextReader.cs 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561
  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. [MonoTODO]
  209. public override char QuoteChar
  210. {
  211. get { throw new NotImplementedException (); }
  212. }
  213. public override ReadState ReadState
  214. {
  215. get { return readState; }
  216. }
  217. public override string Value
  218. {
  219. get { return value; }
  220. }
  221. public WhitespaceHandling WhitespaceHandling
  222. {
  223. get { return whitespaceHandling; }
  224. set { whitespaceHandling = value; }
  225. }
  226. [MonoTODO]
  227. public override string XmlLang
  228. {
  229. get { throw new NotImplementedException (); }
  230. }
  231. [MonoTODO]
  232. public XmlResolver XmlResolver
  233. {
  234. set { throw new NotImplementedException (); }
  235. }
  236. [MonoTODO]
  237. public override XmlSpace XmlSpace
  238. {
  239. get { throw new NotImplementedException (); }
  240. }
  241. #endregion
  242. #region Methods
  243. [MonoTODO]
  244. public override void Close ()
  245. {
  246. readState = ReadState.Closed;
  247. }
  248. [MonoTODO]
  249. public override string GetAttribute (int i)
  250. {
  251. if (i > attributes.Count)
  252. throw new ArgumentOutOfRangeException ("i is smaller than AttributeCount");
  253. else
  254. throw new NotImplementedException ();
  255. }
  256. public override string GetAttribute (string name)
  257. {
  258. return attributes.ContainsKey (name) ?
  259. attributes [name] as string : String.Empty;
  260. }
  261. public override string GetAttribute (string localName, string namespaceURI)
  262. {
  263. foreach (DictionaryEntry entry in attributes)
  264. {
  265. string thisName = entry.Key as string;
  266. int indexOfColon = thisName.IndexOf (':');
  267. if (indexOfColon != -1) {
  268. string thisLocalName = thisName.Substring (indexOfColon + 1);
  269. if (localName == thisLocalName) {
  270. string thisPrefix = thisName.Substring (0, indexOfColon);
  271. string thisNamespaceURI = LookupNamespace (thisPrefix);
  272. if (namespaceURI == thisNamespaceURI)
  273. return attributes.ContainsKey (thisName) ?
  274. attributes [thisName] as string : String.Empty;
  275. }
  276. } else if (localName == "xmlns" && namespaceURI == "http://www.w3.org/2000/xmlns/" && thisName == "xmlns")
  277. return attributes.ContainsKey (thisName) ?
  278. attributes [thisName] as string : String.Empty;
  279. }
  280. return String.Empty;
  281. }
  282. [MonoTODO]
  283. public TextReader GetRemainder ()
  284. {
  285. throw new NotImplementedException ();
  286. }
  287. [MonoTODO]
  288. bool IXmlLineInfo.HasLineInfo ()
  289. {
  290. return false;
  291. }
  292. public override string LookupNamespace (string prefix)
  293. {
  294. return parserContext.NamespaceManager.LookupNamespace (prefix);
  295. }
  296. [MonoTODO]
  297. public override void MoveToAttribute (int i)
  298. {
  299. throw new NotImplementedException ();
  300. }
  301. public override bool MoveToAttribute (string name)
  302. {
  303. MoveToElement ();
  304. bool match = false;
  305. if (attributes == null)
  306. return false;
  307. if (orderedAttributesEnumerator == null) {
  308. SaveProperties ();
  309. orderedAttributesEnumerator = orderedAttributes.GetEnumerator ();
  310. }
  311. while (orderedAttributesEnumerator.MoveNext ()) {
  312. if(name == orderedAttributesEnumerator.Current as string) {
  313. match = true;
  314. break;
  315. }
  316. }
  317. if (match) {
  318. string value = attributes [name] as string;
  319. SetProperties (
  320. XmlNodeType.Attribute, // nodeType
  321. name, // name
  322. false, // isEmptyElement
  323. value, // value
  324. false // clearAttributes
  325. );
  326. }
  327. return match;
  328. }
  329. [MonoTODO]
  330. public override bool MoveToAttribute (string localName, string namespaceName)
  331. {
  332. throw new NotImplementedException ();
  333. }
  334. public override bool MoveToElement ()
  335. {
  336. if (orderedAttributesEnumerator != null) {
  337. orderedAttributesEnumerator = null;
  338. RestoreProperties ();
  339. return true;
  340. }
  341. return false;
  342. }
  343. public override bool MoveToFirstAttribute ()
  344. {
  345. MoveToElement ();
  346. return MoveToNextAttribute ();
  347. }
  348. public override bool MoveToNextAttribute ()
  349. {
  350. if (attributes == null)
  351. return false;
  352. if (orderedAttributesEnumerator == null) {
  353. SaveProperties ();
  354. orderedAttributesEnumerator = orderedAttributes.GetEnumerator ();
  355. }
  356. if (orderedAttributesEnumerator.MoveNext ()) {
  357. string name = orderedAttributesEnumerator.Current as string;
  358. string value = attributes [name] as string;
  359. SetProperties (
  360. XmlNodeType.Attribute, // nodeType
  361. name, // name
  362. false, // isEmptyElement
  363. value, // value
  364. false // clearAttributes
  365. );
  366. return true;
  367. }
  368. return false;
  369. }
  370. public override bool Read ()
  371. {
  372. bool more = false;
  373. readState = ReadState.Interactive;
  374. more = ReadContent ();
  375. return more;
  376. }
  377. [MonoTODO("This method should check position validity; consider entity references")]
  378. public override bool ReadAttributeValue ()
  379. {
  380. value = ReadAttribute ();
  381. return true;
  382. }
  383. [MonoTODO]
  384. public int ReadBase64 (byte [] buffer, int offset, int length)
  385. {
  386. throw new NotImplementedException ();
  387. }
  388. [MonoTODO]
  389. public int ReadBinHex (byte [] buffer, int offset, int length)
  390. {
  391. throw new NotImplementedException ();
  392. }
  393. [MonoTODO]
  394. public int ReadChars (char [] buffer, int offset, int length)
  395. {
  396. throw new NotImplementedException ();
  397. }
  398. [MonoTODO]
  399. public override string ReadInnerXml ()
  400. {
  401. // Still need a Well Formedness check.
  402. // Will wait for Validating reader ;-)
  403. if (NodeType == XmlNodeType.Attribute) {
  404. return Value;
  405. } else {
  406. saveToXmlBuffer = true;
  407. string startname = this.Name;
  408. string endname = string.Empty;
  409. readState = ReadState.Interactive;
  410. while (startname != endname) {
  411. ReadContent ();
  412. endname = this.Name;
  413. }
  414. xmlBuffer.Replace (currentTag.ToString (), "");
  415. saveToXmlBuffer = false;
  416. string InnerXml = xmlBuffer.ToString ();
  417. xmlBuffer.Length = 0;
  418. return InnerXml;
  419. }
  420. }
  421. [MonoTODO]
  422. public override string ReadOuterXml ()
  423. {
  424. if (NodeType == XmlNodeType.Attribute) {
  425. return Name + "=\"" + Value + "\"";
  426. } else {
  427. saveToXmlBuffer = true;
  428. xmlBuffer.Append (currentTag.ToString ());
  429. string startname = this.Name;
  430. string endname = string.Empty;
  431. readState = ReadState.Interactive;
  432. while (startname != endname) {
  433. ReadContent ();
  434. endname = this.Name;
  435. }
  436. saveToXmlBuffer = false;
  437. string OuterXml = xmlBuffer.ToString ();
  438. xmlBuffer.Length = 0;
  439. return OuterXml;
  440. }
  441. }
  442. [MonoTODO]
  443. public override string ReadString ()
  444. {
  445. throw new NotImplementedException ();
  446. }
  447. [MonoTODO]
  448. public void ResetState ()
  449. {
  450. throw new NotImplementedException ();
  451. }
  452. public override void ResolveEntity ()
  453. {
  454. // XmlTextReaders don't resolve entities.
  455. throw new InvalidOperationException ("XmlTextReaders don't resolve entities.");
  456. }
  457. #endregion
  458. // privates
  459. private XmlParserContext parserContext;
  460. private TextReader reader;
  461. private ReadState readState;
  462. private int depth;
  463. private int elementDepth;
  464. private bool depthDown;
  465. private bool popScope;
  466. private XmlNodeType nodeType;
  467. private string name;
  468. private string prefix;
  469. private string localName;
  470. private string namespaceURI;
  471. private bool isEmptyElement;
  472. private string value;
  473. private XmlNodeType saveNodeType;
  474. private string saveName;
  475. private string savePrefix;
  476. private string saveLocalName;
  477. private string saveNamespaceURI;
  478. private bool saveIsEmptyElement;
  479. private Hashtable attributes;
  480. private ArrayList orderedAttributes;
  481. private IEnumerator orderedAttributesEnumerator;
  482. private bool returnEntityReference;
  483. private string entityReferenceName;
  484. private char [] nameBuffer;
  485. private int nameLength;
  486. private int nameCapacity;
  487. private const int initialNameCapacity = 256;
  488. private char [] valueBuffer;
  489. private int valueLength;
  490. private int valueCapacity;
  491. private const int initialValueCapacity = 8192;
  492. private StringBuilder xmlBuffer; // This is for Read(Inner|Outer)Xml
  493. private StringBuilder currentTag; // A buffer for ReadContent for ReadOuterXml
  494. private bool saveToXmlBuffer;
  495. private int line = 1;
  496. private int column = 1;
  497. private bool has_peek;
  498. private bool can_seek;
  499. private int peek_char;
  500. internal string publicId;
  501. internal string systemId;
  502. internal void SetReaderContext (string url, XmlParserContext context)
  503. {
  504. parserContext = context;
  505. parserContext.BaseURI = url;
  506. Init ();
  507. }
  508. internal void SetReaderFragment(TextReader fragment, XmlNodeType fragType)
  509. {
  510. this.reader = fragment;
  511. can_seek = fragment != null && fragment.Peek () != -1;
  512. /* for future use
  513. switch(fragType)
  514. {
  515. case XmlNodeType.Attribute: // attribute content
  516. parserContext.InputState = XmlParserInputState.AttributeValue;
  517. break;
  518. case XmlNodeType.DocumentFragment: // element content
  519. parserContext.InputState = XmlParserInputState.Content;
  520. break;
  521. case XmlNodeType.Element: // one element
  522. parserContext.InputState = XmlParserInputState.StartTag;
  523. break;
  524. case XmlNodeType.Document: // document content
  525. parserContext.InputState = XmlParserInputState.Start;
  526. break;
  527. default:
  528. throw new InvalidOperationException("setting this xml node type not allowed.");
  529. }
  530. */
  531. }
  532. private void Init ()
  533. {
  534. readState = ReadState.Initial;
  535. depth = 0;
  536. depthDown = false;
  537. popScope = false;
  538. nodeType = XmlNodeType.None;
  539. name = String.Empty;
  540. prefix = String.Empty;
  541. localName = string.Empty;
  542. isEmptyElement = false;
  543. value = String.Empty;
  544. attributes = new Hashtable ();
  545. orderedAttributes = new ArrayList ();
  546. orderedAttributesEnumerator = null;
  547. returnEntityReference = false;
  548. entityReferenceName = String.Empty;
  549. nameBuffer = new char [initialNameCapacity];
  550. nameLength = 0;
  551. nameCapacity = initialNameCapacity;
  552. valueBuffer = new char [initialValueCapacity];
  553. valueLength = 0;
  554. valueCapacity = initialValueCapacity;
  555. xmlBuffer = new StringBuilder ();
  556. currentTag = new StringBuilder ();
  557. }
  558. // Use this method rather than setting the properties
  559. // directly so that all the necessary properties can
  560. // be changed in harmony with each other. Maybe the
  561. // fields should be in a seperate class to help enforce
  562. // this.
  563. private void SetProperties (
  564. XmlNodeType nodeType,
  565. string name,
  566. bool isEmptyElement,
  567. string value,
  568. bool clearAttributes)
  569. {
  570. this.nodeType = nodeType;
  571. this.name = name;
  572. this.isEmptyElement = isEmptyElement;
  573. this.value = value;
  574. this.elementDepth = depth;
  575. if (clearAttributes)
  576. ClearAttributes ();
  577. int indexOfColon = name.IndexOf (':');
  578. if (indexOfColon == -1) {
  579. prefix = String.Empty;
  580. localName = name;
  581. } else {
  582. prefix = name.Substring (0, indexOfColon);
  583. localName = name.Substring (indexOfColon + 1);
  584. }
  585. namespaceURI = LookupNamespace (prefix);
  586. }
  587. private void SaveProperties ()
  588. {
  589. saveNodeType = nodeType;
  590. saveName = name;
  591. savePrefix = prefix;
  592. saveLocalName = localName;
  593. saveNamespaceURI = namespaceURI;
  594. saveIsEmptyElement = isEmptyElement;
  595. // An element's value is always String.Empty.
  596. }
  597. private void RestoreProperties ()
  598. {
  599. nodeType = saveNodeType;
  600. name = saveName;
  601. prefix = savePrefix;
  602. localName = saveLocalName;
  603. namespaceURI = saveNamespaceURI;
  604. isEmptyElement = saveIsEmptyElement;
  605. value = String.Empty;
  606. }
  607. private void AddAttribute (string name, string value)
  608. {
  609. attributes.Add (name, value);
  610. orderedAttributes.Add (name);
  611. }
  612. private void ClearAttributes ()
  613. {
  614. if (attributes.Count > 0) {
  615. attributes.Clear ();
  616. orderedAttributes.Clear ();
  617. }
  618. orderedAttributesEnumerator = null;
  619. }
  620. private int PeekChar ()
  621. {
  622. if (can_seek)
  623. return reader.Peek ();
  624. if (has_peek)
  625. return peek_char;
  626. peek_char = reader.Read ();
  627. has_peek = true;
  628. return peek_char;
  629. }
  630. private int ReadChar ()
  631. {
  632. int ch;
  633. if (has_peek) {
  634. ch = peek_char;
  635. has_peek = false;
  636. } else {
  637. ch = reader.Read ();
  638. }
  639. if (ch == '\n') {
  640. line++;
  641. column = 1;
  642. } else {
  643. column++;
  644. }
  645. if (saveToXmlBuffer) {
  646. xmlBuffer.Append ((char) ch);
  647. }
  648. currentTag.Append ((char) ch);
  649. return ch;
  650. }
  651. // This should really keep track of some state so
  652. // that it's not possible to have more than one document
  653. // element or text outside of the document element.
  654. private bool ReadContent ()
  655. {
  656. currentTag.Length = 0;
  657. if (popScope) {
  658. parserContext.NamespaceManager.PopScope ();
  659. popScope = false;
  660. }
  661. if (returnEntityReference) {
  662. SetEntityReferenceProperties ();
  663. } else {
  664. switch (PeekChar ())
  665. {
  666. case '<':
  667. ReadChar ();
  668. ReadTag ();
  669. break;
  670. case '\r':
  671. if (whitespaceHandling == WhitespaceHandling.All ||
  672. whitespaceHandling == WhitespaceHandling.Significant)
  673. return ReadWhitespace ();
  674. ReadChar ();
  675. return ReadContent ();
  676. case '\n':
  677. if (whitespaceHandling == WhitespaceHandling.All ||
  678. whitespaceHandling == WhitespaceHandling.Significant)
  679. return ReadWhitespace ();
  680. ReadChar ();
  681. return ReadContent ();
  682. case ' ':
  683. if (whitespaceHandling == WhitespaceHandling.All ||
  684. whitespaceHandling == WhitespaceHandling.Significant)
  685. return ReadWhitespace ();
  686. SkipWhitespace ();
  687. return ReadContent ();
  688. case -1:
  689. readState = ReadState.EndOfFile;
  690. SetProperties (
  691. XmlNodeType.None, // nodeType
  692. String.Empty, // name
  693. false, // isEmptyElement
  694. String.Empty, // value
  695. true // clearAttributes
  696. );
  697. break;
  698. default:
  699. ReadText (true);
  700. break;
  701. }
  702. }
  703. return this.ReadState != ReadState.EndOfFile;
  704. }
  705. private void SetEntityReferenceProperties ()
  706. {
  707. SetProperties (
  708. XmlNodeType.EntityReference, // nodeType
  709. entityReferenceName, // name
  710. false, // isEmptyElement
  711. String.Empty, // value
  712. true // clearAttributes
  713. );
  714. returnEntityReference = false;
  715. entityReferenceName = String.Empty;
  716. }
  717. // The leading '<' has already been consumed.
  718. private void ReadTag ()
  719. {
  720. switch (PeekChar ())
  721. {
  722. case '/':
  723. ReadChar ();
  724. ReadEndTag ();
  725. break;
  726. case '?':
  727. ReadChar ();
  728. ReadProcessingInstruction ();
  729. break;
  730. case '!':
  731. ReadChar ();
  732. ReadDeclaration ();
  733. break;
  734. default:
  735. ReadStartTag ();
  736. break;
  737. }
  738. }
  739. // The leading '<' has already been consumed.
  740. private void ReadStartTag ()
  741. {
  742. parserContext.NamespaceManager.PushScope ();
  743. string name = ReadName ();
  744. SkipWhitespace ();
  745. bool isEmptyElement = false;
  746. ClearAttributes ();
  747. if (XmlChar.IsFirstNameChar (PeekChar ()))
  748. ReadAttributes ();
  749. if (PeekChar () == '/') {
  750. ReadChar ();
  751. isEmptyElement = true;
  752. depthDown = true;
  753. popScope = true;
  754. }
  755. Expect ('>');
  756. SetProperties (
  757. XmlNodeType.Element, // nodeType
  758. name, // name
  759. isEmptyElement, // isEmptyElement
  760. String.Empty, // value
  761. false // clearAttributes
  762. );
  763. if (!depthDown)
  764. ++depth;
  765. else
  766. depthDown = false;
  767. }
  768. // The reader is positioned on the first character
  769. // of the element's name.
  770. private void ReadEndTag ()
  771. {
  772. string name = ReadName ();
  773. SkipWhitespace ();
  774. Expect ('>');
  775. --depth;
  776. SetProperties (
  777. XmlNodeType.EndElement, // nodeType
  778. name, // name
  779. false, // isEmptyElement
  780. String.Empty, // value
  781. true // clearAttributes
  782. );
  783. popScope = true;
  784. }
  785. private void AppendNameChar (int ch)
  786. {
  787. CheckNameCapacity ();
  788. nameBuffer [nameLength++] = (char)ch;
  789. }
  790. private void CheckNameCapacity ()
  791. {
  792. if (nameLength == nameCapacity) {
  793. nameCapacity = nameCapacity * 2;
  794. char [] oldNameBuffer = nameBuffer;
  795. nameBuffer = new char [nameCapacity];
  796. Array.Copy (oldNameBuffer, nameBuffer, nameLength);
  797. }
  798. }
  799. private string CreateNameString ()
  800. {
  801. return new String (nameBuffer, 0, nameLength);
  802. }
  803. private void AppendValueChar (int ch)
  804. {
  805. CheckValueCapacity ();
  806. valueBuffer [valueLength++] = (char)ch;
  807. }
  808. private void CheckValueCapacity ()
  809. {
  810. if (valueLength == valueCapacity) {
  811. valueCapacity = valueCapacity * 2;
  812. char [] oldValueBuffer = valueBuffer;
  813. valueBuffer = new char [valueCapacity];
  814. Array.Copy (oldValueBuffer, valueBuffer, valueLength);
  815. }
  816. }
  817. private string CreateValueString ()
  818. {
  819. return new String (valueBuffer, 0, valueLength);
  820. }
  821. // The reader is positioned on the first character
  822. // of the text.
  823. private void ReadText (bool cleanValue)
  824. {
  825. if (cleanValue)
  826. valueLength = 0;
  827. int ch = PeekChar ();
  828. while (ch != '<' && ch != -1) {
  829. if (ch == '&') {
  830. ReadChar ();
  831. if (ReadReference (false))
  832. break;
  833. } else
  834. AppendValueChar (ReadChar ());
  835. ch = PeekChar ();
  836. }
  837. if (returnEntityReference && valueLength == 0) {
  838. SetEntityReferenceProperties ();
  839. } else {
  840. SetProperties (
  841. XmlNodeType.Text, // nodeType
  842. String.Empty, // name
  843. false, // isEmptyElement
  844. CreateValueString (), // value
  845. true // clearAttributes
  846. );
  847. }
  848. }
  849. // The leading '&' has already been consumed.
  850. // Returns true if the entity reference isn't a simple
  851. // character reference or one of the predefined entities.
  852. // This allows the ReadText method to break so that the
  853. // next call to Read will return the EntityReference node.
  854. private bool ReadReference (bool ignoreEntityReferences)
  855. {
  856. if (PeekChar () == '#') {
  857. ReadChar ();
  858. ReadCharacterReference ();
  859. } else
  860. ReadEntityReference (ignoreEntityReferences);
  861. return returnEntityReference;
  862. }
  863. private void ReadCharacterReference ()
  864. {
  865. int value = 0;
  866. if (PeekChar () == 'x') {
  867. ReadChar ();
  868. while (PeekChar () != ';' && PeekChar () != -1) {
  869. int ch = ReadChar ();
  870. if (ch >= '0' && ch <= '9')
  871. value = (value << 4) + ch - '0';
  872. else if (ch >= 'A' && ch <= 'F')
  873. value = (value << 4) + ch - 'A' + 10;
  874. else if (ch >= 'a' && ch <= 'f')
  875. value = (value << 4) + ch - 'a' + 10;
  876. else
  877. throw new XmlException (
  878. String.Format (
  879. "invalid hexadecimal digit: {0} (#x{1:X})",
  880. (char)ch,
  881. ch));
  882. }
  883. } else {
  884. while (PeekChar () != ';' && PeekChar () != -1) {
  885. int ch = ReadChar ();
  886. if (ch >= '0' && ch <= '9')
  887. value = value * 10 + ch - '0';
  888. else
  889. throw new XmlException (
  890. String.Format (
  891. "invalid decimal digit: {0} (#x{1:X})",
  892. (char)ch,
  893. ch));
  894. }
  895. }
  896. ReadChar (); // ';'
  897. AppendValueChar (value);
  898. }
  899. private void ReadEntityReference (bool ignoreEntityReferences)
  900. {
  901. nameLength = 0;
  902. int ch = PeekChar ();
  903. while (ch != ';' && ch != -1) {
  904. AppendNameChar (ReadChar ());
  905. ch = PeekChar ();
  906. }
  907. Expect (';');
  908. string name = CreateNameString ();
  909. switch (name)
  910. {
  911. case "lt":
  912. AppendValueChar ('<');
  913. break;
  914. case "gt":
  915. AppendValueChar ('>');
  916. break;
  917. case "amp":
  918. AppendValueChar ('&');
  919. break;
  920. case "apos":
  921. AppendValueChar ('\'');
  922. break;
  923. case "quot":
  924. AppendValueChar ('"');
  925. break;
  926. default:
  927. if (ignoreEntityReferences) {
  928. AppendValueChar ('&');
  929. foreach (char ch2 in name) {
  930. AppendValueChar (ch2);
  931. }
  932. AppendValueChar (';');
  933. } else {
  934. returnEntityReference = true;
  935. entityReferenceName = name;
  936. }
  937. break;
  938. }
  939. }
  940. // The reader is positioned on the first character of
  941. // the attribute name.
  942. private void ReadAttributes ()
  943. {
  944. do {
  945. string name = ReadName ();
  946. SkipWhitespace ();
  947. Expect ('=');
  948. SkipWhitespace ();
  949. string value = ReadAttribute ();
  950. SkipWhitespace ();
  951. if (name == "xmlns")
  952. parserContext.NamespaceManager.AddNamespace (String.Empty, value);
  953. else if (name.StartsWith ("xmlns:"))
  954. parserContext.NamespaceManager.AddNamespace (name.Substring (6), value);
  955. AddAttribute (name, value);
  956. } while (PeekChar () != '/' && PeekChar () != '>' && PeekChar () != -1);
  957. }
  958. // The reader is positioned on the quote character.
  959. private string ReadAttribute ()
  960. {
  961. int quoteChar = ReadChar ();
  962. if (quoteChar != '\'' && quoteChar != '\"')
  963. throw new XmlException ("an attribute value was not quoted");
  964. valueLength = 0;
  965. while (PeekChar () != quoteChar) {
  966. int ch = ReadChar ();
  967. switch (ch)
  968. {
  969. case '<':
  970. throw new XmlException ("attribute values cannot contain '<'");
  971. case '&':
  972. ReadReference (true);
  973. break;
  974. case -1:
  975. throw new XmlException ("unexpected end of file in an attribute value");
  976. default:
  977. AppendValueChar (ch);
  978. break;
  979. }
  980. }
  981. ReadChar (); // quoteChar
  982. return CreateValueString ();
  983. }
  984. // The reader is positioned on the first character
  985. // of the target.
  986. //
  987. // Now it also reads XmlDeclaration, this method name became improper...
  988. private void ReadProcessingInstruction ()
  989. {
  990. string target = ReadName ();
  991. SkipWhitespace ();
  992. valueLength = 0;
  993. while (PeekChar () != -1) {
  994. int ch = ReadChar ();
  995. if (ch == '?' && PeekChar () == '>') {
  996. ReadChar ();
  997. break;
  998. }
  999. AppendValueChar ((char)ch);
  1000. }
  1001. /* for future use
  1002. if(target == "xml") && parserContext.InputState != XmlParserInputState.Start)
  1003. throw new XmlException("Xml declaration is not allowed here.");
  1004. else {
  1005. parserContext.InputState = XmlParserInputState.DTD; //for future use
  1006. }
  1007. */
  1008. SetProperties (
  1009. target == "xml" ?
  1010. XmlNodeType.XmlDeclaration :
  1011. XmlNodeType.ProcessingInstruction, // nodeType
  1012. target, // name
  1013. false, // isEmptyElement
  1014. CreateValueString (), // value
  1015. true // clearAttributes
  1016. );
  1017. }
  1018. // The reader is positioned on the first character after
  1019. // the leading '<!'.
  1020. private void ReadDeclaration ()
  1021. {
  1022. int ch = PeekChar ();
  1023. switch (ch)
  1024. {
  1025. case '-':
  1026. Expect ("--");
  1027. ReadComment ();
  1028. break;
  1029. case '[':
  1030. ReadChar ();
  1031. Expect ("CDATA[");
  1032. ReadCDATA ();
  1033. break;
  1034. case 'D':
  1035. Expect ("DOCTYPE");
  1036. ReadDoctypeDecl ();
  1037. break;
  1038. }
  1039. }
  1040. // The reader is positioned on the first character after
  1041. // the leading '<!--'.
  1042. private void ReadComment ()
  1043. {
  1044. valueLength = 0;
  1045. while (PeekChar () != -1) {
  1046. int ch = ReadChar ();
  1047. if (ch == '-' && PeekChar () == '-') {
  1048. ReadChar ();
  1049. if (PeekChar () != '>')
  1050. throw new XmlException ("comments cannot contain '--'");
  1051. ReadChar ();
  1052. break;
  1053. }
  1054. AppendValueChar ((char)ch);
  1055. }
  1056. SetProperties (
  1057. XmlNodeType.Comment, // nodeType
  1058. String.Empty, // name
  1059. false, // isEmptyElement
  1060. CreateValueString (), // value
  1061. true // clearAttributes
  1062. );
  1063. }
  1064. // The reader is positioned on the first character after
  1065. // the leading '<![CDATA['.
  1066. private void ReadCDATA ()
  1067. {
  1068. valueLength = 0;
  1069. while (PeekChar () != -1) {
  1070. int ch = ReadChar ();
  1071. if (ch == ']' && PeekChar () == ']') {
  1072. ch = ReadChar (); // ']'
  1073. if (PeekChar () == '>') {
  1074. ReadChar (); // '>'
  1075. break;
  1076. } else {
  1077. AppendValueChar (']');
  1078. AppendValueChar (']');
  1079. ch = ReadChar ();
  1080. }
  1081. }
  1082. AppendValueChar ((char)ch);
  1083. }
  1084. SetProperties (
  1085. XmlNodeType.CDATA, // nodeType
  1086. String.Empty, // name
  1087. false, // isEmptyElement
  1088. CreateValueString (), // value
  1089. true // clearAttributes
  1090. );
  1091. }
  1092. // The reader is positioned on the first character after
  1093. // the leading '<!DOCTYPE'.
  1094. private void ReadDoctypeDecl ()
  1095. {
  1096. string doctypeName = null;
  1097. string publicId = String.Empty;
  1098. string systemId = String.Empty;
  1099. SkipWhitespace ();
  1100. doctypeName = ReadName ();
  1101. SkipWhitespace ();
  1102. xmlBuffer.Length = 0;
  1103. switch(PeekChar ())
  1104. {
  1105. case 'S':
  1106. systemId = ReadSystemLiteral (true);
  1107. break;
  1108. case 'P':
  1109. publicId = ReadPubidLiteral ();
  1110. SkipWhitespace ();
  1111. systemId = ReadSystemLiteral (false);
  1112. break;
  1113. }
  1114. SkipWhitespace ();
  1115. if(PeekChar () == '[')
  1116. {
  1117. // read markupdecl etc. or end of decl
  1118. ReadChar ();
  1119. xmlBuffer.Length = 0;
  1120. saveToXmlBuffer = true;
  1121. do {
  1122. ReadDTDInternalSubset ();
  1123. } while(nodeType != XmlNodeType.None);
  1124. xmlBuffer.Remove (xmlBuffer.Length - 1, 1); // cut off ']'
  1125. saveToXmlBuffer = false;
  1126. }
  1127. // end of DOCTYPE decl.
  1128. SkipWhitespace ();
  1129. Expect ('>');
  1130. parserContext.InternalSubset = xmlBuffer.ToString ();
  1131. // set properties for <!DOCTYPE> node
  1132. SetProperties (
  1133. XmlNodeType.DocumentType, // nodeType
  1134. doctypeName, // name
  1135. false, // isEmptyElement
  1136. parserContext.InternalSubset, // value
  1137. true // clearAttributes
  1138. );
  1139. }
  1140. // Read any one of following:
  1141. // elementdecl, AttlistDecl, EntityDecl, NotationDecl,
  1142. // PI, Comment, Parameter Entity, or doctype termination char(']')
  1143. //
  1144. // returns a node of some nodeType or null, setting nodeType.
  1145. // (if None then ']' was found.)
  1146. private void ReadDTDInternalSubset()
  1147. {
  1148. SkipWhitespace ();
  1149. switch(ReadChar ())
  1150. {
  1151. case ']':
  1152. nodeType = XmlNodeType.None;
  1153. break;
  1154. case '%':
  1155. string peName = ReadName ();
  1156. Expect (';');
  1157. nodeType = XmlNodeType.EntityReference; // It's chating a bit;-)
  1158. break;
  1159. case '<':
  1160. switch(ReadChar ())
  1161. {
  1162. case '?':
  1163. ReadProcessingInstruction ();
  1164. break;
  1165. case '!':
  1166. switch(ReadChar ())
  1167. {
  1168. case '-':
  1169. Expect ('-');
  1170. ReadComment ();
  1171. break;
  1172. case 'E':
  1173. switch(ReadChar ())
  1174. {
  1175. case 'N':
  1176. Expect ("TITY");
  1177. ReadEntityDecl ();
  1178. break;
  1179. case 'L':
  1180. Expect ("EMENT");
  1181. ReadElementDecl ();
  1182. break;
  1183. default:
  1184. throw new XmlException ("Syntax Error after '<!E' (ELEMENT or ENTITY must be found)");
  1185. }
  1186. break;
  1187. case 'A':
  1188. Expect ("TTLIST");
  1189. ReadAttListDecl ();
  1190. break;
  1191. case 'N':
  1192. Expect ("OTATION");
  1193. ReadNotationDecl ();
  1194. break;
  1195. default:
  1196. throw new XmlException ("Syntax Error after '<!' characters.");
  1197. }
  1198. break;
  1199. default:
  1200. throw new XmlException ("Syntax Error after '<' character.");
  1201. }
  1202. break;
  1203. default:
  1204. throw new XmlException ("Syntax Error inside doctypedecl markup.");
  1205. }
  1206. }
  1207. // The reader is positioned on the head of the name.
  1208. private void ReadElementDecl()
  1209. {
  1210. while(ReadChar () != '>');
  1211. }
  1212. private void ReadEntityDecl()
  1213. {
  1214. while(ReadChar () != '>');
  1215. }
  1216. private void ReadAttListDecl()
  1217. {
  1218. while(ReadChar () != '>');
  1219. }
  1220. private void ReadNotationDecl()
  1221. {
  1222. while(ReadChar () != '>');
  1223. }
  1224. // The reader is positioned on the first 'S' of "SYSTEM".
  1225. private string ReadSystemLiteral (bool expectSYSTEM)
  1226. {
  1227. if(expectSYSTEM)
  1228. Expect ("SYSTEM");
  1229. SkipWhitespace ();
  1230. int quoteChar = ReadChar (); // apos or quot
  1231. xmlBuffer.Length = 0;
  1232. saveToXmlBuffer = true;
  1233. int c = 0;
  1234. while(c != quoteChar) {
  1235. c = ReadChar ();
  1236. if(c < 0) throw new XmlException ("Unexpected end of stream in ExternalID.");
  1237. }
  1238. saveToXmlBuffer = false;
  1239. xmlBuffer.Remove (xmlBuffer.Length-1, 1); // cut quoteChar
  1240. return xmlBuffer.ToString ();
  1241. }
  1242. private string ReadPubidLiteral()
  1243. {
  1244. Expect ("PUBLIC");
  1245. SkipWhitespace ();
  1246. int quoteChar = ReadChar ();
  1247. xmlBuffer.Length = 0;
  1248. saveToXmlBuffer = true;
  1249. int c = 0;
  1250. while(c != quoteChar)
  1251. {
  1252. c = ReadChar ();
  1253. if(c < 0) throw new XmlException ("Unexpected end of stream in ExternalID.");
  1254. if(c != quoteChar && !XmlChar.IsPubidChar (c))
  1255. throw new XmlException("character '" + (char)c + "' not allowed for PUBLIC ID");
  1256. }
  1257. ReadChar(); // skips quoteChar
  1258. xmlBuffer.Remove (xmlBuffer.Length-1, 1); // cut quoteChar
  1259. saveToXmlBuffer = false;
  1260. return xmlBuffer.ToString ();
  1261. }
  1262. // The reader is positioned on the first character
  1263. // of the name.
  1264. private string ReadName ()
  1265. {
  1266. if (!XmlChar.IsFirstNameChar (PeekChar ()))
  1267. throw new XmlException ("a name did not start with a legal character");
  1268. nameLength = 0;
  1269. AppendNameChar (ReadChar ());
  1270. while (XmlChar.IsNameChar (PeekChar ())) {
  1271. AppendNameChar (ReadChar ());
  1272. }
  1273. return CreateNameString ();
  1274. }
  1275. // Read the next character and compare it against the
  1276. // specified character.
  1277. private void Expect (int expected)
  1278. {
  1279. int ch = ReadChar ();
  1280. if (ch != expected) {
  1281. throw new XmlException (
  1282. String.Format (
  1283. "expected '{0}' ({1:X}) but found '{2}' ({3:X})",
  1284. (char)expected,
  1285. expected,
  1286. (char)ch,
  1287. ch));
  1288. }
  1289. }
  1290. private void Expect (string expected)
  1291. {
  1292. int len = expected.Length;
  1293. for(int i=0; i< len; i++)
  1294. Expect (expected[i]);
  1295. }
  1296. // Does not consume the first non-whitespace character.
  1297. private void SkipWhitespace ()
  1298. {
  1299. //FIXME: Should not skip if whitespaceHandling == WhiteSpaceHandling.None
  1300. while (XmlChar.IsWhitespace (PeekChar ()))
  1301. ReadChar ();
  1302. }
  1303. private bool ReadWhitespace ()
  1304. {
  1305. valueLength = 0;
  1306. int ch = PeekChar ();
  1307. do {
  1308. AppendValueChar (ReadChar ());
  1309. } while ((ch = PeekChar ()) != -1 && XmlChar.IsWhitespace (ch));
  1310. if (ch != -1 && ch != '<')
  1311. ReadText (false);
  1312. else
  1313. SetProperties (XmlNodeType.Whitespace,
  1314. String.Empty,
  1315. false,
  1316. CreateValueString (),
  1317. true);
  1318. return (PeekChar () != -1);
  1319. }
  1320. }
  1321. }