XmlTextReader.cs 39 KB

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