XmlReader.cs 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  1. //
  2. // XmlReader.cs
  3. //
  4. // Authors:
  5. // Jason Diamond ([email protected])
  6. // Gonzalo Paniagua Javier ([email protected])
  7. // Atsushi Enomoto ([email protected])
  8. //
  9. // (C) 2001, 2002 Jason Diamond http://injektilo.org/
  10. // (c) 2002 Ximian, Inc. (http://www.ximian.com)
  11. // (C) 2003 Atsushi Enomoto
  12. //
  13. //
  14. // Permission is hereby granted, free of charge, to any person obtaining
  15. // a copy of this software and associated documentation files (the
  16. // "Software"), to deal in the Software without restriction, including
  17. // without limitation the rights to use, copy, modify, merge, publish,
  18. // distribute, sublicense, and/or sell copies of the Software, and to
  19. // permit persons to whom the Software is furnished to do so, subject to
  20. // the following conditions:
  21. //
  22. // The above copyright notice and this permission notice shall be
  23. // included in all copies or substantial portions of the Software.
  24. //
  25. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  28. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  29. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. //
  33. using System.Collections;
  34. using System.Diagnostics;
  35. using System.IO;
  36. using System.Text;
  37. using System.Xml.Schema; // only required for NET_2_0 (SchemaInfo)
  38. using System.Xml.Serialization; // only required for NET_2_0 (SchemaInfo)
  39. using Mono.Xml; // only required for NET_2_0
  40. using Mono.Xml.Schema; // only required for NET_2_0
  41. namespace System.Xml
  42. {
  43. #if NET_2_0
  44. public abstract class XmlReader : IDisposable
  45. #else
  46. public abstract class XmlReader
  47. #endif
  48. {
  49. private StringBuilder readStringBuffer;
  50. private XmlReaderBinarySupport binary;
  51. #if NET_2_0
  52. private XmlReaderSettings settings;
  53. #endif
  54. #region Constructor
  55. protected XmlReader ()
  56. {
  57. }
  58. #endregion
  59. #region Properties
  60. public abstract int AttributeCount { get; }
  61. public abstract string BaseURI { get; }
  62. internal XmlReaderBinarySupport Binary {
  63. get { return binary; }
  64. }
  65. internal XmlReaderBinarySupport.CharGetter BinaryCharGetter {
  66. get { return binary != null ? binary.Getter : null; }
  67. set {
  68. if (binary == null)
  69. binary = new XmlReaderBinarySupport (this);
  70. binary.Getter = value;
  71. }
  72. }
  73. #if NET_2_0
  74. // To enable it internally in sys.xml, just insert these
  75. // two lines into Read():
  76. //
  77. // #if NET_2_0
  78. // if (Binary != null)
  79. // Binary.Reset ();
  80. // #endif
  81. //
  82. public virtual bool CanReadBinaryContent {
  83. get { return false; }
  84. }
  85. public virtual bool CanReadValueChunk {
  86. get { return false; }
  87. }
  88. #else
  89. internal virtual bool CanReadBinaryContent {
  90. get { return false; }
  91. }
  92. internal virtual bool CanReadValueChunk {
  93. get { return false; }
  94. }
  95. #endif
  96. public virtual bool CanResolveEntity
  97. {
  98. get { return false; }
  99. }
  100. public abstract int Depth { get; }
  101. public abstract bool EOF { get; }
  102. public virtual bool HasAttributes
  103. {
  104. get { return AttributeCount > 0; }
  105. }
  106. public abstract bool HasValue { get; }
  107. public abstract bool IsEmptyElement { get; }
  108. #if NET_2_0
  109. public virtual bool IsDefault {
  110. get { return false; }
  111. }
  112. public virtual string this [int i] {
  113. get { return GetAttribute (i); }
  114. }
  115. public virtual string this [string name] {
  116. get { return GetAttribute (name); }
  117. }
  118. public virtual string this [string name, string namespaceURI] {
  119. get { return GetAttribute (name, namespaceURI); }
  120. }
  121. #else
  122. public abstract bool IsDefault { get; }
  123. public abstract string this [int i] { get; }
  124. public abstract string this [string name] { get; }
  125. public abstract string this [string localName, string namespaceName] { get; }
  126. #endif
  127. public abstract string LocalName { get; }
  128. #if NET_2_0
  129. public virtual string Name {
  130. get {
  131. return Prefix.Length > 0 ?
  132. String.Concat (Prefix, ":", LocalName) :
  133. LocalName;
  134. }
  135. }
  136. #else
  137. public abstract string Name { get; }
  138. #endif
  139. public abstract string NamespaceURI { get; }
  140. public abstract XmlNameTable NameTable { get; }
  141. public abstract XmlNodeType NodeType { get; }
  142. public abstract string Prefix { get; }
  143. #if NET_2_0
  144. public virtual char QuoteChar {
  145. get { return '\"'; }
  146. }
  147. #else
  148. public abstract char QuoteChar { get; }
  149. #endif
  150. public abstract ReadState ReadState { get; }
  151. #if NET_2_0
  152. public virtual IXmlSchemaInfo SchemaInfo {
  153. get { return null; }
  154. }
  155. public virtual XmlReaderSettings Settings {
  156. get { return settings; }
  157. }
  158. #endif
  159. public abstract string Value { get; }
  160. #if NET_2_0
  161. public virtual string XmlLang {
  162. get { return String.Empty; }
  163. }
  164. public virtual XmlSpace XmlSpace {
  165. get { return XmlSpace.None; }
  166. }
  167. #else
  168. public abstract string XmlLang { get; }
  169. public abstract XmlSpace XmlSpace { get; }
  170. #endif
  171. #endregion
  172. #region Methods
  173. public abstract void Close ();
  174. #if NET_2_0
  175. private static XmlNameTable PopulateNameTable (
  176. XmlReaderSettings settings)
  177. {
  178. XmlNameTable nameTable = settings.NameTable;
  179. if (nameTable == null)
  180. nameTable = new NameTable ();
  181. return nameTable;
  182. }
  183. private static XmlParserContext PopulateParserContext (
  184. XmlReaderSettings settings, string baseUri)
  185. {
  186. XmlNameTable nt = PopulateNameTable (settings);
  187. return new XmlParserContext (nt,
  188. new XmlNamespaceManager (nt),
  189. baseUri,
  190. XmlSpace.None);
  191. }
  192. private static XmlNodeType GetNodeType (
  193. XmlReaderSettings settings)
  194. {
  195. ConformanceLevel level = settings != null ? settings.ConformanceLevel : ConformanceLevel.Auto;
  196. return
  197. level == ConformanceLevel.Fragment ?
  198. XmlNodeType.Element :
  199. XmlNodeType.Document;
  200. }
  201. public static XmlReader Create (Stream stream)
  202. {
  203. return Create (stream, null);
  204. }
  205. public static XmlReader Create (string url)
  206. {
  207. return Create (url, null);
  208. }
  209. public static XmlReader Create (TextReader reader)
  210. {
  211. return Create (reader, null);
  212. }
  213. public static XmlReader Create (string url, XmlReaderSettings settings)
  214. {
  215. return Create (url, settings, null);
  216. }
  217. public static XmlReader Create (Stream stream, XmlReaderSettings settings)
  218. {
  219. return Create (stream, settings, String.Empty);
  220. }
  221. public static XmlReader Create (TextReader reader, XmlReaderSettings settings)
  222. {
  223. return Create (reader, settings, String.Empty);
  224. }
  225. static XmlReaderSettings PopulateSettings (XmlReaderSettings src)
  226. {
  227. if (src == null)
  228. return new XmlReaderSettings ();
  229. else
  230. return src.Clone ();
  231. }
  232. public static XmlReader Create (Stream stream, XmlReaderSettings settings, string baseUri)
  233. {
  234. settings = PopulateSettings (settings);
  235. return Create (stream, settings,
  236. PopulateParserContext (settings, baseUri));
  237. }
  238. public static XmlReader Create (TextReader reader, XmlReaderSettings settings, string baseUri)
  239. {
  240. settings = PopulateSettings (settings);
  241. return Create (reader, settings,
  242. PopulateParserContext (settings, baseUri));
  243. }
  244. public static XmlReader Create (XmlReader reader, XmlReaderSettings settings)
  245. {
  246. settings = PopulateSettings (settings);
  247. XmlReader r = CreateFilteredXmlReader (reader, settings);
  248. r.settings = settings;
  249. return r;
  250. }
  251. public static XmlReader Create (string url, XmlReaderSettings settings, XmlParserContext context)
  252. {
  253. settings = PopulateSettings (settings);
  254. if (context == null)
  255. context = PopulateParserContext (settings, url);
  256. XmlTextReader xtr = new XmlTextReader (false, settings.XmlResolver, url, GetNodeType (settings), context);
  257. XmlReader ret = CreateCustomizedTextReader (xtr, settings);
  258. xtr.CloseInput = true;
  259. return xtr;
  260. }
  261. public static XmlReader Create (Stream stream, XmlReaderSettings settings, XmlParserContext context)
  262. {
  263. settings = PopulateSettings (settings);
  264. if (context == null)
  265. context = PopulateParserContext (settings, String.Empty);
  266. return CreateCustomizedTextReader (new XmlTextReader (stream, GetNodeType (settings), context), settings);
  267. }
  268. public static XmlReader Create (TextReader reader, XmlReaderSettings settings, XmlParserContext context)
  269. {
  270. settings = PopulateSettings (settings);
  271. if (context == null)
  272. context = PopulateParserContext (settings, String.Empty);
  273. return CreateCustomizedTextReader (new XmlTextReader (context.BaseURI, reader, GetNodeType (settings), context), settings);
  274. }
  275. private static XmlReader CreateCustomizedTextReader (XmlTextReader reader, XmlReaderSettings settings)
  276. {
  277. reader.XmlResolver = settings.XmlResolver;
  278. // Normalization is set true by default.
  279. reader.Normalization = true;
  280. if (settings.ProhibitDtd)
  281. reader.ProhibitDtd = true;
  282. if (!settings.CheckCharacters)
  283. reader.CharacterChecking = false;
  284. // I guess it might be changed in 2.0 RTM to set true
  285. // as default, or just disappear. It goes against
  286. // XmlTextReader's default usage and users will have
  287. // to close input manually (that's annoying). Moreover,
  288. // MS XmlTextReader consumes text input more than
  289. // actually read and users can acquire those extra
  290. // consumption by GetRemainder() that returns different
  291. // TextReader.
  292. reader.CloseInput = settings.CloseInput;
  293. // I would like to support it in detail later;
  294. // MSDN description looks source of confusion. We don't
  295. // need examples, but precise list of how it works.
  296. reader.Conformance = settings.ConformanceLevel;
  297. reader.AdjustLineInfoOffset (settings.LineNumberOffset,
  298. settings.LinePositionOffset);
  299. if (settings.NameTable != null)
  300. reader.SetNameTable (settings.NameTable);
  301. XmlReader r = CreateFilteredXmlReader (reader, settings);
  302. r.settings = settings;
  303. return r;
  304. }
  305. private static XmlReader CreateFilteredXmlReader (XmlReader reader, XmlReaderSettings settings)
  306. {
  307. ConformanceLevel conf = ConformanceLevel.Auto;
  308. if (reader is XmlTextReader)
  309. conf = ((XmlTextReader) reader).Conformance;
  310. else if (reader.Settings != null)
  311. conf = reader.Settings.ConformanceLevel;
  312. else
  313. conf = settings.ConformanceLevel;
  314. if (settings.ConformanceLevel != ConformanceLevel.Auto &&
  315. conf != settings.ConformanceLevel)
  316. throw new InvalidOperationException (String.Format ("ConformanceLevel cannot be overwritten by a wrapping XmlReader. The source reader has {0}, while {1} is specified.", conf, settings.ConformanceLevel));
  317. settings.ConformanceLevel = conf;
  318. reader = CreateValidatingXmlReader (reader, settings);
  319. if (reader.Settings != null ||
  320. settings.IgnoreComments ||
  321. settings.IgnoreProcessingInstructions ||
  322. settings.IgnoreWhitespace)
  323. return new XmlFilterReader (reader, settings);
  324. else {
  325. reader.settings = settings;
  326. return reader;
  327. }
  328. }
  329. private static XmlReader CreateValidatingXmlReader (XmlReader reader, XmlReaderSettings settings)
  330. {
  331. XmlValidatingReader xvr = null;
  332. switch (settings.ValidationType) {
  333. // Auto and XDR are obsoleted in 2.0 and therefore ignored.
  334. default:
  335. return reader;
  336. case ValidationType.DTD:
  337. xvr = new XmlValidatingReader (reader);
  338. xvr.XmlResolver = settings.XmlResolver;
  339. xvr.ValidationType = ValidationType.DTD;
  340. break;
  341. case ValidationType.Schema:
  342. return new XmlSchemaValidatingReader (reader, settings);
  343. }
  344. // Actually I don't think they are treated in DTD validation though...
  345. if ((settings.ValidationFlags & XmlSchemaValidationFlags.ProcessIdentityConstraints) == 0)
  346. throw new NotImplementedException ();
  347. //if ((settings.ValidationFlags & XmlSchemaValidationFlags.ProcessInlineSchema) != 0)
  348. // throw new NotImplementedException ();
  349. //if ((settings.ValidationFlags & XmlSchemaValidationFlags.ProcessSchemaLocation) != 0)
  350. // throw new NotImplementedException ();
  351. //if ((settings.ValidationFlags & XmlSchemaValidationFlags.ReportValidationWarnings) == 0)
  352. // throw new NotImplementedException ();
  353. return xvr != null ? xvr : reader;
  354. }
  355. #endif
  356. #if NET_2_0
  357. void IDisposable.Dispose ()
  358. {
  359. Dispose (false);
  360. }
  361. protected virtual void Dispose (bool disposing)
  362. {
  363. if (ReadState != ReadState.Closed)
  364. Close ();
  365. }
  366. #endif
  367. public abstract string GetAttribute (int i);
  368. public abstract string GetAttribute (string name);
  369. public abstract string GetAttribute (
  370. string localName,
  371. string namespaceName);
  372. public static bool IsName (string s)
  373. {
  374. return s != null && XmlChar.IsName (s);
  375. }
  376. public static bool IsNameToken (string s)
  377. {
  378. return s != null && XmlChar.IsNmToken (s);
  379. }
  380. public virtual bool IsStartElement ()
  381. {
  382. return (MoveToContent () == XmlNodeType.Element);
  383. }
  384. public virtual bool IsStartElement (string name)
  385. {
  386. if (!IsStartElement ())
  387. return false;
  388. return (Name == name);
  389. }
  390. public virtual bool IsStartElement (string localName, string namespaceName)
  391. {
  392. if (!IsStartElement ())
  393. return false;
  394. return (LocalName == localName && NamespaceURI == namespaceName);
  395. }
  396. public abstract string LookupNamespace (string prefix);
  397. #if NET_2_0
  398. public virtual void MoveToAttribute (int i)
  399. {
  400. if (i >= AttributeCount)
  401. throw new ArgumentOutOfRangeException ();
  402. MoveToFirstAttribute ();
  403. for (int a = 0; a < i; a++)
  404. MoveToNextAttribute ();
  405. }
  406. #else
  407. public abstract void MoveToAttribute (int i);
  408. #endif
  409. public abstract bool MoveToAttribute (string name);
  410. public abstract bool MoveToAttribute (
  411. string localName,
  412. string namespaceName);
  413. private bool IsContent (XmlNodeType nodeType)
  414. {
  415. /* MS doc says:
  416. * (non-white space text, CDATA, Element, EndElement, EntityReference, or EndEntity)
  417. */
  418. switch (nodeType) {
  419. case XmlNodeType.Text:
  420. return true;
  421. case XmlNodeType.CDATA:
  422. return true;
  423. case XmlNodeType.Element:
  424. return true;
  425. case XmlNodeType.EndElement:
  426. return true;
  427. case XmlNodeType.EntityReference:
  428. return true;
  429. case XmlNodeType.EndEntity:
  430. return true;
  431. }
  432. return false;
  433. }
  434. public virtual XmlNodeType MoveToContent ()
  435. {
  436. if (NodeType == XmlNodeType.Attribute)
  437. MoveToElement ();
  438. do {
  439. if (IsContent (NodeType))
  440. return NodeType;
  441. Read ();
  442. } while (!EOF);
  443. return XmlNodeType.None;
  444. }
  445. public abstract bool MoveToElement ();
  446. public abstract bool MoveToFirstAttribute ();
  447. public abstract bool MoveToNextAttribute ();
  448. public abstract bool Read ();
  449. public abstract bool ReadAttributeValue ();
  450. public virtual string ReadElementString ()
  451. {
  452. if (MoveToContent () != XmlNodeType.Element) {
  453. string error = String.Format ("'{0}' is an invalid node type.",
  454. NodeType.ToString ());
  455. throw XmlError (error);
  456. }
  457. string result = String.Empty;
  458. if (!IsEmptyElement) {
  459. Read ();
  460. result = ReadString ();
  461. if (NodeType != XmlNodeType.EndElement) {
  462. string error = String.Format ("'{0}' is an invalid node type.",
  463. NodeType.ToString ());
  464. throw XmlError (error);
  465. }
  466. }
  467. Read ();
  468. return result;
  469. }
  470. public virtual string ReadElementString (string name)
  471. {
  472. if (MoveToContent () != XmlNodeType.Element) {
  473. string error = String.Format ("'{0}' is an invalid node type.",
  474. NodeType.ToString ());
  475. throw XmlError (error);
  476. }
  477. if (name != Name) {
  478. string error = String.Format ("The {0} tag from namespace {1} is expected.",
  479. Name, NamespaceURI);
  480. throw XmlError (error);
  481. }
  482. string result = String.Empty;
  483. if (!IsEmptyElement) {
  484. Read ();
  485. result = ReadString ();
  486. if (NodeType != XmlNodeType.EndElement) {
  487. string error = String.Format ("'{0}' is an invalid node type.",
  488. NodeType.ToString ());
  489. throw XmlError (error);
  490. }
  491. }
  492. Read ();
  493. return result;
  494. }
  495. public virtual string ReadElementString (string localName, string namespaceName)
  496. {
  497. if (MoveToContent () != XmlNodeType.Element) {
  498. string error = String.Format ("'{0}' is an invalid node type.",
  499. NodeType.ToString ());
  500. throw XmlError (error);
  501. }
  502. if (localName != LocalName || NamespaceURI != namespaceName) {
  503. string error = String.Format ("The {0} tag from namespace {1} is expected.",
  504. LocalName, NamespaceURI);
  505. throw XmlError (error);
  506. }
  507. string result = String.Empty;
  508. if (!IsEmptyElement) {
  509. Read ();
  510. result = ReadString ();
  511. if (NodeType != XmlNodeType.EndElement) {
  512. string error = String.Format ("'{0}' is an invalid node type.",
  513. NodeType.ToString ());
  514. throw XmlError (error);
  515. }
  516. }
  517. Read ();
  518. return result;
  519. }
  520. public virtual void ReadEndElement ()
  521. {
  522. if (MoveToContent () != XmlNodeType.EndElement) {
  523. string error = String.Format ("'{0}' is an invalid node type.",
  524. NodeType.ToString ());
  525. throw XmlError (error);
  526. }
  527. Read ();
  528. }
  529. public virtual string ReadInnerXml ()
  530. {
  531. if (ReadState != ReadState.Interactive || NodeType == XmlNodeType.EndElement)
  532. return String.Empty;
  533. if (IsEmptyElement) {
  534. Read ();
  535. return String.Empty;
  536. }
  537. StringWriter sw = new StringWriter ();
  538. XmlTextWriter xtw = new XmlTextWriter (sw);
  539. if (NodeType == XmlNodeType.Element) {
  540. int startDepth = Depth;
  541. Read ();
  542. while (startDepth < Depth) {
  543. if (ReadState != ReadState.Interactive)
  544. throw XmlError ("Unexpected end of the XML reader.");
  545. xtw.WriteNode (this, false);
  546. }
  547. // reader is now end element, then proceed once more.
  548. Read ();
  549. }
  550. else
  551. xtw.WriteNode (this, false);
  552. return sw.ToString ();
  553. }
  554. public virtual string ReadOuterXml ()
  555. {
  556. if (ReadState != ReadState.Interactive || NodeType == XmlNodeType.EndElement)
  557. return String.Empty;
  558. switch (NodeType) {
  559. case XmlNodeType.Element:
  560. case XmlNodeType.Attribute:
  561. StringWriter sw = new StringWriter ();
  562. XmlTextWriter xtw = new XmlTextWriter (sw);
  563. xtw.WriteNode (this, false);
  564. return sw.ToString ();
  565. default:
  566. Skip ();
  567. return String.Empty;
  568. }
  569. }
  570. public virtual void ReadStartElement ()
  571. {
  572. if (MoveToContent () != XmlNodeType.Element) {
  573. string error = String.Format ("'{0}' is an invalid node type.",
  574. NodeType.ToString ());
  575. throw XmlError (error);
  576. }
  577. Read ();
  578. }
  579. public virtual void ReadStartElement (string name)
  580. {
  581. if (MoveToContent () != XmlNodeType.Element) {
  582. string error = String.Format ("'{0}' is an invalid node type.",
  583. NodeType.ToString ());
  584. throw XmlError (error);
  585. }
  586. if (name != Name) {
  587. string error = String.Format ("The {0} tag from namespace {1} is expected.",
  588. Name, NamespaceURI);
  589. throw XmlError (error);
  590. }
  591. Read ();
  592. }
  593. public virtual void ReadStartElement (string localName, string namespaceName)
  594. {
  595. if (MoveToContent () != XmlNodeType.Element) {
  596. string error = String.Format ("'{0}' is an invalid node type.",
  597. NodeType.ToString ());
  598. throw XmlError (error);
  599. }
  600. if (localName != LocalName || NamespaceURI != namespaceName) {
  601. string error = String.Format ("Expecting {0} tag from namespace {1}, got {2} and {3} instead",
  602. localName, namespaceName,
  603. LocalName, NamespaceURI);
  604. throw XmlError (error);
  605. }
  606. Read ();
  607. }
  608. public virtual string ReadString ()
  609. {
  610. if (readStringBuffer == null)
  611. readStringBuffer = new StringBuilder ();
  612. readStringBuffer.Length = 0;
  613. MoveToElement ();
  614. switch (NodeType) {
  615. default:
  616. return String.Empty;
  617. case XmlNodeType.Element:
  618. if (IsEmptyElement)
  619. return String.Empty;
  620. do {
  621. Read ();
  622. switch (NodeType) {
  623. case XmlNodeType.Text:
  624. case XmlNodeType.CDATA:
  625. case XmlNodeType.Whitespace:
  626. case XmlNodeType.SignificantWhitespace:
  627. readStringBuffer.Append (Value);
  628. continue;
  629. }
  630. break;
  631. } while (true);
  632. break;
  633. case XmlNodeType.Text:
  634. case XmlNodeType.CDATA:
  635. case XmlNodeType.Whitespace:
  636. case XmlNodeType.SignificantWhitespace:
  637. do {
  638. switch (NodeType) {
  639. case XmlNodeType.Text:
  640. case XmlNodeType.CDATA:
  641. case XmlNodeType.Whitespace:
  642. case XmlNodeType.SignificantWhitespace:
  643. readStringBuffer.Append (Value);
  644. Read ();
  645. continue;
  646. }
  647. break;
  648. } while (true);
  649. break;
  650. }
  651. string ret = readStringBuffer.ToString ();
  652. readStringBuffer.Length = 0;
  653. return ret;
  654. }
  655. #if NET_2_0
  656. public virtual Type ValueType {
  657. get { return typeof (string); }
  658. }
  659. public virtual bool ReadToDescendant (string name)
  660. {
  661. if (ReadState == ReadState.Initial) {
  662. MoveToContent ();
  663. if (IsStartElement (name))
  664. return true;
  665. }
  666. if (NodeType != XmlNodeType.Element || IsEmptyElement)
  667. return false;
  668. int depth = Depth;
  669. for (Read (); depth < Depth; Read ())
  670. if (NodeType == XmlNodeType.Element && name == Name)
  671. return true;
  672. return false;
  673. }
  674. public virtual bool ReadToDescendant (string localName, string namespaceURI)
  675. {
  676. if (ReadState == ReadState.Initial) {
  677. MoveToContent ();
  678. if (IsStartElement (localName, namespaceURI))
  679. return true;
  680. }
  681. if (NodeType != XmlNodeType.Element || IsEmptyElement)
  682. return false;
  683. int depth = Depth;
  684. for (Read (); depth < Depth; Read ())
  685. if (NodeType == XmlNodeType.Element && localName == LocalName && namespaceURI == NamespaceURI)
  686. return true;
  687. return false;
  688. }
  689. public virtual bool ReadToFollowing (string name)
  690. {
  691. while (Read ())
  692. if (NodeType == XmlNodeType.Element && name == Name)
  693. return true;
  694. return false;
  695. }
  696. public virtual bool ReadToFollowing (string localName, string namespaceURI)
  697. {
  698. while (Read ())
  699. if (NodeType == XmlNodeType.Element && localName == Name && namespaceURI == NamespaceURI)
  700. return true;
  701. return false;
  702. }
  703. public virtual bool ReadToNextSibling (string name)
  704. {
  705. if (ReadState != ReadState.Interactive)
  706. return false;
  707. int depth = Depth;
  708. for (Skip (); depth >= Depth; Skip ())
  709. if (NodeType == XmlNodeType.Element && name == Name)
  710. return true;
  711. return false;
  712. }
  713. public virtual bool ReadToNextSibling (string localName, string namespaceURI)
  714. {
  715. if (ReadState != ReadState.Interactive)
  716. return false;
  717. int depth = Depth;
  718. for (Skip (); depth >= Depth; Skip ())
  719. if (NodeType == XmlNodeType.Element && localName == LocalName && namespaceURI == NamespaceURI)
  720. return true;
  721. return false;
  722. }
  723. public virtual XmlReader ReadSubtree ()
  724. {
  725. return new SubtreeXmlReader (this);
  726. }
  727. private string ReadContentString ()
  728. {
  729. if (NodeType == XmlNodeType.Attribute)
  730. return Value;
  731. return ReadContentString (true);
  732. }
  733. private string ReadContentString (bool isText)
  734. {
  735. if (isText) {
  736. switch (NodeType) {
  737. case XmlNodeType.Text:
  738. case XmlNodeType.SignificantWhitespace:
  739. case XmlNodeType.Whitespace:
  740. case XmlNodeType.CDATA:
  741. break;
  742. default:
  743. throw new InvalidOperationException (String.Format ("Node type {0} is not supported in this operation.{1}", NodeType, GetLocation ()));
  744. }
  745. }
  746. string value = String.Empty;
  747. do {
  748. switch (NodeType) {
  749. case XmlNodeType.Element:
  750. if (isText)
  751. return value;
  752. throw XmlError ("Child element is not expected in this operation.");
  753. case XmlNodeType.EndElement:
  754. return value;
  755. case XmlNodeType.Text:
  756. case XmlNodeType.CDATA:
  757. case XmlNodeType.SignificantWhitespace:
  758. case XmlNodeType.Whitespace:
  759. value += Value;
  760. break;
  761. }
  762. } while (Read ());
  763. throw XmlError ("Unexpected end of document.");
  764. }
  765. string GetLocation ()
  766. {
  767. IXmlLineInfo li = this as IXmlLineInfo;
  768. return li != null && li.HasLineInfo () ?
  769. String.Format (" {0} (line {1}, column {2})", BaseURI, li.LineNumber, li.LinePosition) : String.Empty;
  770. }
  771. [MonoTODO]
  772. public virtual object ReadElementContentAsObject ()
  773. {
  774. return ReadElementContentAs (ValueType, null);
  775. }
  776. [MonoTODO]
  777. public virtual object ReadElementContentAsObject (string localName, string namespaceURI)
  778. {
  779. return ReadElementContentAs (ValueType, null, localName, namespaceURI);
  780. }
  781. [MonoTODO]
  782. public virtual object ReadContentAsObject ()
  783. {
  784. return ReadContentAs (ValueType, null);
  785. }
  786. public virtual object ReadElementContentAs (Type type, IXmlNamespaceResolver resolver)
  787. {
  788. bool isEmpty = IsEmptyElement;
  789. ReadStartElement ();
  790. object obj = ValueAs (isEmpty ? String.Empty : ReadContentString (false), type, resolver);
  791. if (!isEmpty)
  792. ReadEndElement ();
  793. return obj;
  794. }
  795. public virtual object ReadElementContentAs (Type type, IXmlNamespaceResolver resolver, string localName, string namespaceURI)
  796. {
  797. ReadStartElement (localName, namespaceURI);
  798. object obj = ReadContentAs (type, resolver);
  799. ReadEndElement ();
  800. return obj;
  801. }
  802. public virtual object ReadContentAs (Type type, IXmlNamespaceResolver resolver)
  803. {
  804. return ValueAs (ReadContentString (), type, resolver);
  805. }
  806. private object ValueAs (string text, Type type, IXmlNamespaceResolver resolver)
  807. {
  808. try {
  809. if (type == typeof (object))
  810. return text;
  811. if (type == typeof (XmlQualifiedName)) {
  812. if (resolver != null)
  813. return XmlQualifiedName.Parse (text, resolver);
  814. else
  815. return XmlQualifiedName.Parse (text, this);
  816. }
  817. switch (Type.GetTypeCode (type)) {
  818. case TypeCode.Boolean:
  819. return XQueryConvert.StringToBoolean (text);
  820. case TypeCode.DateTime:
  821. return XQueryConvert.StringToDateTime (text);
  822. case TypeCode.Decimal:
  823. return XQueryConvert.StringToDecimal (text);
  824. case TypeCode.Double:
  825. return XQueryConvert.StringToDouble (text);
  826. case TypeCode.Int32:
  827. return XQueryConvert.StringToInt (text);
  828. case TypeCode.Int64:
  829. return XQueryConvert.StringToInteger (text);
  830. case TypeCode.Single:
  831. return XQueryConvert.StringToFloat (text);
  832. case TypeCode.String:
  833. return text;
  834. }
  835. } catch (Exception ex) {
  836. throw XmlError (String.Format ("Current text value '{0}' is not acceptable for specified type '{1}'. {2}", text, type, ex != null ? ex.Message : String.Empty), ex);
  837. }
  838. throw new ArgumentException (String.Format ("Specified type '{0}' is not supported.", type));
  839. }
  840. public virtual bool ReadElementContentAsBoolean ()
  841. {
  842. try {
  843. return XQueryConvert.StringToBoolean (ReadElementContentAsString ());
  844. } catch (FormatException ex) {
  845. throw XmlError ("Typed value is invalid.", ex);
  846. }
  847. }
  848. public virtual DateTime ReadElementContentAsDateTime ()
  849. {
  850. try {
  851. return XQueryConvert.StringToDateTime (ReadElementContentAsString ());
  852. } catch (FormatException ex) {
  853. throw XmlError ("Typed value is invalid.", ex);
  854. }
  855. }
  856. public virtual decimal ReadElementContentAsDecimal ()
  857. {
  858. try {
  859. return XQueryConvert.StringToDecimal (ReadElementContentAsString ());
  860. } catch (FormatException ex) {
  861. throw XmlError ("Typed value is invalid.", ex);
  862. }
  863. }
  864. public virtual double ReadElementContentAsDouble ()
  865. {
  866. try {
  867. return XQueryConvert.StringToDouble (ReadElementContentAsString ());
  868. } catch (FormatException ex) {
  869. throw XmlError ("Typed value is invalid.", ex);
  870. }
  871. }
  872. public virtual float ReadElementContentAsFloat ()
  873. {
  874. try {
  875. return XQueryConvert.StringToFloat (ReadElementContentAsString ());
  876. } catch (FormatException ex) {
  877. throw XmlError ("Typed value is invalid.", ex);
  878. }
  879. }
  880. public virtual int ReadElementContentAsInt ()
  881. {
  882. try {
  883. return XQueryConvert.StringToInt (ReadElementContentAsString ());
  884. } catch (FormatException ex) {
  885. throw XmlError ("Typed value is invalid.", ex);
  886. }
  887. }
  888. public virtual long ReadElementContentAsLong ()
  889. {
  890. try {
  891. return XQueryConvert.StringToInteger (ReadElementContentAsString ());
  892. } catch (FormatException ex) {
  893. throw XmlError ("Typed value is invalid.", ex);
  894. }
  895. }
  896. public virtual string ReadElementContentAsString ()
  897. {
  898. bool isEmpty = IsEmptyElement;
  899. ReadStartElement ();
  900. if (isEmpty)
  901. return String.Empty;
  902. string s = ReadContentString (false);
  903. ReadEndElement ();
  904. return s;
  905. }
  906. public virtual bool ReadElementContentAsBoolean (string localName, string namespaceURI)
  907. {
  908. try {
  909. return XQueryConvert.StringToBoolean (ReadElementContentAsString (localName, namespaceURI));
  910. } catch (FormatException ex) {
  911. throw XmlError ("Typed value is invalid.", ex);
  912. }
  913. }
  914. public virtual DateTime ReadElementContentAsDateTime (string localName, string namespaceURI)
  915. {
  916. try {
  917. return XQueryConvert.StringToDateTime (ReadElementContentAsString (localName, namespaceURI));
  918. } catch (FormatException ex) {
  919. throw XmlError ("Typed value is invalid.", ex);
  920. }
  921. }
  922. public virtual decimal ReadElementContentAsDecimal (string localName, string namespaceURI)
  923. {
  924. try {
  925. return XQueryConvert.StringToDecimal (ReadElementContentAsString (localName, namespaceURI));
  926. } catch (FormatException ex) {
  927. throw XmlError ("Typed value is invalid.", ex);
  928. }
  929. }
  930. public virtual double ReadElementContentAsDouble (string localName, string namespaceURI)
  931. {
  932. try {
  933. return XQueryConvert.StringToDouble (ReadElementContentAsString (localName, namespaceURI));
  934. } catch (FormatException ex) {
  935. throw XmlError ("Typed value is invalid.", ex);
  936. }
  937. }
  938. public virtual float ReadElementContentAsFloat (string localName, string namespaceURI)
  939. {
  940. try {
  941. return XQueryConvert.StringToFloat (ReadElementContentAsString (localName, namespaceURI));
  942. } catch (FormatException ex) {
  943. throw XmlError ("Typed value is invalid.", ex);
  944. }
  945. }
  946. public virtual int ReadElementContentAsInt (string localName, string namespaceURI)
  947. {
  948. try {
  949. return XQueryConvert.StringToInt (ReadElementContentAsString (localName, namespaceURI));
  950. } catch (FormatException ex) {
  951. throw XmlError ("Typed value is invalid.", ex);
  952. }
  953. }
  954. public virtual long ReadElementContentAsLong (string localName, string namespaceURI)
  955. {
  956. try {
  957. return XQueryConvert.StringToInteger (ReadElementContentAsString (localName, namespaceURI));
  958. } catch (FormatException ex) {
  959. throw XmlError ("Typed value is invalid.", ex);
  960. }
  961. }
  962. public virtual string ReadElementContentAsString (string localName, string namespaceURI)
  963. {
  964. ReadStartElement (localName, namespaceURI);
  965. if (IsEmptyElement)
  966. return String.Empty;
  967. string s = ReadContentString (false);
  968. ReadEndElement ();
  969. return s;
  970. }
  971. public virtual bool ReadContentAsBoolean ()
  972. {
  973. try {
  974. return XQueryConvert.StringToBoolean (ReadContentString ());
  975. } catch (FormatException ex) {
  976. throw XmlError ("Typed value is invalid.", ex);
  977. }
  978. }
  979. public virtual DateTime ReadContentAsDateTime ()
  980. {
  981. try {
  982. return XQueryConvert.StringToDateTime (ReadContentString ());
  983. } catch (FormatException ex) {
  984. throw XmlError ("Typed value is invalid.", ex);
  985. }
  986. }
  987. public virtual decimal ReadContentAsDecimal ()
  988. {
  989. try {
  990. return XQueryConvert.StringToDecimal (ReadContentString ());
  991. } catch (FormatException ex) {
  992. throw XmlError ("Typed value is invalid.", ex);
  993. }
  994. }
  995. public virtual double ReadContentAsDouble ()
  996. {
  997. try {
  998. return XQueryConvert.StringToDouble (ReadContentString ());
  999. } catch (FormatException ex) {
  1000. throw XmlError ("Typed value is invalid.", ex);
  1001. }
  1002. }
  1003. public virtual float ReadContentAsFloat ()
  1004. {
  1005. try {
  1006. return XQueryConvert.StringToFloat (ReadContentString ());
  1007. } catch (FormatException ex) {
  1008. throw XmlError ("Typed value is invalid.", ex);
  1009. }
  1010. }
  1011. public virtual int ReadContentAsInt ()
  1012. {
  1013. try {
  1014. return XQueryConvert.StringToInt (ReadContentString ());
  1015. } catch (FormatException ex) {
  1016. throw XmlError ("Typed value is invalid.", ex);
  1017. }
  1018. }
  1019. public virtual long ReadContentAsLong ()
  1020. {
  1021. try {
  1022. return XQueryConvert.StringToInteger (ReadContentString ());
  1023. } catch (FormatException ex) {
  1024. throw XmlError ("Typed value is invalid.", ex);
  1025. }
  1026. }
  1027. public virtual string ReadContentAsString ()
  1028. {
  1029. return ReadContentString ();
  1030. }
  1031. public virtual int ReadContentAsBase64 (
  1032. byte [] buffer, int offset, int length)
  1033. {
  1034. CheckSupport ();
  1035. return binary.ReadContentAsBase64 (
  1036. buffer, offset, length);
  1037. }
  1038. public virtual int ReadContentAsBinHex (
  1039. byte [] buffer, int offset, int length)
  1040. {
  1041. CheckSupport ();
  1042. return binary.ReadContentAsBinHex (
  1043. buffer, offset, length);
  1044. }
  1045. public virtual int ReadElementContentAsBase64 (
  1046. byte [] buffer, int offset, int length)
  1047. {
  1048. CheckSupport ();
  1049. return binary.ReadElementContentAsBase64 (
  1050. buffer, offset, length);
  1051. }
  1052. public virtual int ReadElementContentAsBinHex (
  1053. byte [] buffer, int offset, int length)
  1054. {
  1055. CheckSupport ();
  1056. return binary.ReadElementContentAsBinHex (
  1057. buffer, offset, length);
  1058. }
  1059. #endif
  1060. #if NET_2_0
  1061. public virtual int ReadValueChunk (
  1062. char [] buffer, int offset, int length)
  1063. #else
  1064. internal virtual int ReadValueChunk (
  1065. char [] buffer, int offset, int length)
  1066. #endif
  1067. {
  1068. if (!CanReadValueChunk)
  1069. throw new NotSupportedException ();
  1070. if (binary == null)
  1071. binary = new XmlReaderBinarySupport (this);
  1072. return binary.ReadValueChunk (buffer, offset, length);
  1073. }
  1074. private void CheckSupport ()
  1075. {
  1076. // Default implementation expects both.
  1077. if (!CanReadBinaryContent || !CanReadValueChunk)
  1078. throw new NotSupportedException ();
  1079. if (binary == null)
  1080. binary = new XmlReaderBinarySupport (this);
  1081. }
  1082. public abstract void ResolveEntity ();
  1083. public virtual void Skip ()
  1084. {
  1085. if (ReadState != ReadState.Interactive)
  1086. return;
  1087. MoveToElement ();
  1088. if (NodeType != XmlNodeType.Element || IsEmptyElement) {
  1089. Read ();
  1090. return;
  1091. }
  1092. int depth = Depth;
  1093. while (Read () && depth < Depth)
  1094. ;
  1095. if (NodeType == XmlNodeType.EndElement)
  1096. Read ();
  1097. }
  1098. private XmlException XmlError (string message)
  1099. {
  1100. return new XmlException (this as IXmlLineInfo, BaseURI, message);
  1101. }
  1102. private XmlException XmlError (string message, Exception innerException)
  1103. {
  1104. return new XmlException (this as IXmlLineInfo, BaseURI, message);
  1105. }
  1106. #endregion
  1107. }
  1108. }