XmlReader.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  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. return CreateCustomizedTextReader (
  257. new XmlTextReader (true, url, GetNodeType (settings), context),
  258. settings);
  259. }
  260. public static XmlReader Create (Stream stream, XmlReaderSettings settings, XmlParserContext context)
  261. {
  262. settings = PopulateSettings (settings);
  263. if (context == null)
  264. context = PopulateParserContext (settings, String.Empty);
  265. return CreateCustomizedTextReader (new XmlTextReader (stream, GetNodeType (settings), context), settings);
  266. }
  267. public static XmlReader Create (TextReader reader, XmlReaderSettings settings, XmlParserContext context)
  268. {
  269. settings = PopulateSettings (settings);
  270. if (context == null)
  271. context = PopulateParserContext (settings, String.Empty);
  272. return CreateCustomizedTextReader (new XmlTextReader (context.BaseURI, reader, GetNodeType (settings), context), settings);
  273. }
  274. private static XmlReader CreateCustomizedTextReader (XmlTextReader reader, XmlReaderSettings settings)
  275. {
  276. reader.XmlResolver = settings.XmlResolver;
  277. // Normalization is set true by default.
  278. reader.Normalization = true;
  279. if (settings.ProhibitDtd)
  280. reader.ProhibitDtd = true;
  281. if (!settings.CheckCharacters)
  282. reader.CharacterChecking = false;
  283. // I guess it might be changed in 2.0 RTM to set true
  284. // as default, or just disappear. It goes against
  285. // XmlTextReader's default usage and users will have
  286. // to close input manually (that's annoying). Moreover,
  287. // MS XmlTextReader consumes text input more than
  288. // actually read and users can acquire those extra
  289. // consumption by GetRemainder() that returns different
  290. // TextReader.
  291. reader.CloseInput = settings.CloseInput;
  292. // I would like to support it in detail later;
  293. // MSDN description looks source of confusion. We don't
  294. // need examples, but precise list of how it works.
  295. reader.Conformance = settings.ConformanceLevel;
  296. reader.AdjustLineInfoOffset (settings.LineNumberOffset,
  297. settings.LinePositionOffset);
  298. if (settings.NameTable != null)
  299. reader.SetNameTable (settings.NameTable);
  300. XmlReader r = CreateFilteredXmlReader (reader, settings);
  301. r.settings = settings;
  302. return r;
  303. }
  304. private static XmlReader CreateFilteredXmlReader (XmlReader reader, XmlReaderSettings settings)
  305. {
  306. ConformanceLevel conf = ConformanceLevel.Auto;
  307. if (reader is XmlTextReader)
  308. conf = ((XmlTextReader) reader).Conformance;
  309. else if (reader.Settings != null)
  310. conf = reader.Settings.ConformanceLevel;
  311. else
  312. conf = settings.ConformanceLevel;
  313. if (settings.ConformanceLevel != ConformanceLevel.Auto &&
  314. conf != settings.ConformanceLevel)
  315. 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));
  316. settings.ConformanceLevel = conf;
  317. reader = CreateValidatingXmlReader (reader, settings);
  318. if (reader.Settings != null ||
  319. settings.IgnoreComments ||
  320. settings.IgnoreProcessingInstructions ||
  321. settings.IgnoreWhitespace)
  322. return new XmlFilterReader (reader, settings);
  323. else {
  324. reader.settings = settings;
  325. return reader;
  326. }
  327. }
  328. private static XmlReader CreateValidatingXmlReader (XmlReader reader, XmlReaderSettings settings)
  329. {
  330. XmlValidatingReader xvr = null;
  331. switch (settings.ValidationType) {
  332. // Auto and XDR are obsoleted in 2.0 and therefore ignored.
  333. default:
  334. return reader;
  335. case ValidationType.DTD:
  336. xvr = new XmlValidatingReader (reader);
  337. xvr.XmlResolver = settings.XmlResolver;
  338. xvr.ValidationType = ValidationType.DTD;
  339. break;
  340. case ValidationType.Schema:
  341. // xvr = new XmlValidatingReader (reader);
  342. // xvr.ValidationType = ValidationType.Schema;
  343. return new XmlSchemaValidatingReader (reader, settings);
  344. }
  345. if (xvr != null)
  346. xvr.SetSchemas (settings.Schemas);
  347. // Actually I don't think they are treated in DTD validation though...
  348. if ((settings.ValidationFlags & XmlSchemaValidationFlags.ProcessIdentityConstraints) == 0)
  349. throw new NotImplementedException ();
  350. if ((settings.ValidationFlags & XmlSchemaValidationFlags.ProcessInlineSchema) != 0)
  351. throw new NotImplementedException ();
  352. if ((settings.ValidationFlags & XmlSchemaValidationFlags.ProcessSchemaLocation) != 0)
  353. throw new NotImplementedException ();
  354. if ((settings.ValidationFlags & XmlSchemaValidationFlags.ReportValidationWarnings) == 0)
  355. throw new NotImplementedException ();
  356. return xvr != null ? xvr : reader;
  357. }
  358. #endif
  359. #if NET_2_0
  360. void IDisposable.Dispose ()
  361. {
  362. Dispose (false);
  363. }
  364. protected virtual void Dispose (bool disposing)
  365. {
  366. if (ReadState != ReadState.Closed)
  367. Close ();
  368. }
  369. #endif
  370. public abstract string GetAttribute (int i);
  371. public abstract string GetAttribute (string name);
  372. public abstract string GetAttribute (
  373. string localName,
  374. string namespaceName);
  375. public static bool IsName (string s)
  376. {
  377. return s != null && XmlChar.IsName (s);
  378. }
  379. public static bool IsNameToken (string s)
  380. {
  381. return s != null && XmlChar.IsNmToken (s);
  382. }
  383. public virtual bool IsStartElement ()
  384. {
  385. return (MoveToContent () == XmlNodeType.Element);
  386. }
  387. public virtual bool IsStartElement (string name)
  388. {
  389. if (!IsStartElement ())
  390. return false;
  391. return (Name == name);
  392. }
  393. public virtual bool IsStartElement (string localName, string namespaceName)
  394. {
  395. if (!IsStartElement ())
  396. return false;
  397. return (LocalName == localName && NamespaceURI == namespaceName);
  398. }
  399. public abstract string LookupNamespace (string prefix);
  400. #if NET_2_0
  401. public virtual void MoveToAttribute (int i)
  402. {
  403. if (i >= AttributeCount)
  404. throw new ArgumentOutOfRangeException ();
  405. MoveToFirstAttribute ();
  406. for (int a = 1; a < i; a++)
  407. MoveToNextAttribute ();
  408. }
  409. #else
  410. public abstract void MoveToAttribute (int i);
  411. #endif
  412. public abstract bool MoveToAttribute (string name);
  413. public abstract bool MoveToAttribute (
  414. string localName,
  415. string namespaceName);
  416. private bool IsContent (XmlNodeType nodeType)
  417. {
  418. /* MS doc says:
  419. * (non-white space text, CDATA, Element, EndElement, EntityReference, or EndEntity)
  420. */
  421. switch (nodeType) {
  422. case XmlNodeType.Text:
  423. return true;
  424. case XmlNodeType.CDATA:
  425. return true;
  426. case XmlNodeType.Element:
  427. return true;
  428. case XmlNodeType.EndElement:
  429. return true;
  430. case XmlNodeType.EntityReference:
  431. return true;
  432. case XmlNodeType.EndEntity:
  433. return true;
  434. }
  435. return false;
  436. }
  437. public virtual XmlNodeType MoveToContent ()
  438. {
  439. if (NodeType == XmlNodeType.Attribute)
  440. MoveToElement ();
  441. do {
  442. if (IsContent (NodeType))
  443. return NodeType;
  444. Read ();
  445. } while (!EOF);
  446. return XmlNodeType.None;
  447. }
  448. public abstract bool MoveToElement ();
  449. public abstract bool MoveToFirstAttribute ();
  450. public abstract bool MoveToNextAttribute ();
  451. public abstract bool Read ();
  452. public abstract bool ReadAttributeValue ();
  453. public virtual string ReadElementString ()
  454. {
  455. if (MoveToContent () != XmlNodeType.Element) {
  456. string error = String.Format ("'{0}' is an invalid node type.",
  457. NodeType.ToString ());
  458. throw XmlError (error);
  459. }
  460. string result = String.Empty;
  461. if (!IsEmptyElement) {
  462. Read ();
  463. result = ReadString ();
  464. if (NodeType != XmlNodeType.EndElement) {
  465. string error = String.Format ("'{0}' is an invalid node type.",
  466. NodeType.ToString ());
  467. throw XmlError (error);
  468. }
  469. }
  470. Read ();
  471. return result;
  472. }
  473. public virtual string ReadElementString (string name)
  474. {
  475. if (MoveToContent () != XmlNodeType.Element) {
  476. string error = String.Format ("'{0}' is an invalid node type.",
  477. NodeType.ToString ());
  478. throw XmlError (error);
  479. }
  480. if (name != Name) {
  481. string error = String.Format ("The {0} tag from namespace {1} is expected.",
  482. Name, NamespaceURI);
  483. throw XmlError (error);
  484. }
  485. string result = String.Empty;
  486. if (!IsEmptyElement) {
  487. Read ();
  488. result = ReadString ();
  489. if (NodeType != XmlNodeType.EndElement) {
  490. string error = String.Format ("'{0}' is an invalid node type.",
  491. NodeType.ToString ());
  492. throw XmlError (error);
  493. }
  494. }
  495. Read ();
  496. return result;
  497. }
  498. public virtual string ReadElementString (string localName, string namespaceName)
  499. {
  500. if (MoveToContent () != XmlNodeType.Element) {
  501. string error = String.Format ("'{0}' is an invalid node type.",
  502. NodeType.ToString ());
  503. throw XmlError (error);
  504. }
  505. if (localName != LocalName || NamespaceURI != namespaceName) {
  506. string error = String.Format ("The {0} tag from namespace {1} is expected.",
  507. LocalName, NamespaceURI);
  508. throw XmlError (error);
  509. }
  510. string result = String.Empty;
  511. if (!IsEmptyElement) {
  512. Read ();
  513. result = ReadString ();
  514. if (NodeType != XmlNodeType.EndElement) {
  515. string error = String.Format ("'{0}' is an invalid node type.",
  516. NodeType.ToString ());
  517. throw XmlError (error);
  518. }
  519. }
  520. Read ();
  521. return result;
  522. }
  523. public virtual void ReadEndElement ()
  524. {
  525. if (MoveToContent () != XmlNodeType.EndElement) {
  526. string error = String.Format ("'{0}' is an invalid node type.",
  527. NodeType.ToString ());
  528. throw XmlError (error);
  529. }
  530. Read ();
  531. }
  532. public virtual string ReadInnerXml ()
  533. {
  534. if (ReadState != ReadState.Interactive || NodeType == XmlNodeType.EndElement)
  535. return String.Empty;
  536. if (IsEmptyElement) {
  537. Read ();
  538. return String.Empty;
  539. }
  540. StringWriter sw = new StringWriter ();
  541. XmlTextWriter xtw = new XmlTextWriter (sw);
  542. if (NodeType == XmlNodeType.Element) {
  543. int startDepth = Depth;
  544. Read ();
  545. while (startDepth < Depth) {
  546. if (ReadState != ReadState.Interactive)
  547. throw XmlError ("Unexpected end of the XML reader.");
  548. xtw.WriteNode (this, false);
  549. }
  550. // reader is now end element, then proceed once more.
  551. Read ();
  552. }
  553. else
  554. xtw.WriteNode (this, false);
  555. return sw.ToString ();
  556. }
  557. public virtual string ReadOuterXml ()
  558. {
  559. if (ReadState != ReadState.Interactive || NodeType == XmlNodeType.EndElement)
  560. return String.Empty;
  561. switch (NodeType) {
  562. case XmlNodeType.Element:
  563. case XmlNodeType.Attribute:
  564. StringWriter sw = new StringWriter ();
  565. XmlTextWriter xtw = new XmlTextWriter (sw);
  566. xtw.WriteNode (this, false);
  567. return sw.ToString ();
  568. default:
  569. Skip ();
  570. return String.Empty;
  571. }
  572. }
  573. public virtual void ReadStartElement ()
  574. {
  575. if (MoveToContent () != XmlNodeType.Element) {
  576. string error = String.Format ("'{0}' is an invalid node type.",
  577. NodeType.ToString ());
  578. throw XmlError (error);
  579. }
  580. Read ();
  581. }
  582. public virtual void ReadStartElement (string name)
  583. {
  584. if (MoveToContent () != XmlNodeType.Element) {
  585. string error = String.Format ("'{0}' is an invalid node type.",
  586. NodeType.ToString ());
  587. throw XmlError (error);
  588. }
  589. if (name != Name) {
  590. string error = String.Format ("The {0} tag from namespace {1} is expected.",
  591. Name, NamespaceURI);
  592. throw XmlError (error);
  593. }
  594. Read ();
  595. }
  596. public virtual void ReadStartElement (string localName, string namespaceName)
  597. {
  598. if (MoveToContent () != XmlNodeType.Element) {
  599. string error = String.Format ("'{0}' is an invalid node type.",
  600. NodeType.ToString ());
  601. throw XmlError (error);
  602. }
  603. if (localName != LocalName || NamespaceURI != namespaceName) {
  604. string error = String.Format ("Expecting {0} tag from namespace {1}, got {2} and {3} instead",
  605. localName, namespaceName,
  606. LocalName, NamespaceURI);
  607. throw XmlError (error);
  608. }
  609. Read ();
  610. }
  611. public virtual string ReadString ()
  612. {
  613. if (readStringBuffer == null)
  614. readStringBuffer = new StringBuilder ();
  615. readStringBuffer.Length = 0;
  616. MoveToElement ();
  617. switch (NodeType) {
  618. default:
  619. return String.Empty;
  620. case XmlNodeType.Element:
  621. if (IsEmptyElement)
  622. return String.Empty;
  623. do {
  624. Read ();
  625. switch (NodeType) {
  626. case XmlNodeType.Text:
  627. case XmlNodeType.CDATA:
  628. case XmlNodeType.Whitespace:
  629. case XmlNodeType.SignificantWhitespace:
  630. readStringBuffer.Append (Value);
  631. continue;
  632. }
  633. break;
  634. } while (true);
  635. break;
  636. case XmlNodeType.Text:
  637. case XmlNodeType.CDATA:
  638. case XmlNodeType.Whitespace:
  639. case XmlNodeType.SignificantWhitespace:
  640. do {
  641. switch (NodeType) {
  642. case XmlNodeType.Text:
  643. case XmlNodeType.CDATA:
  644. case XmlNodeType.Whitespace:
  645. case XmlNodeType.SignificantWhitespace:
  646. readStringBuffer.Append (Value);
  647. Read ();
  648. continue;
  649. }
  650. break;
  651. } while (true);
  652. break;
  653. }
  654. string ret = readStringBuffer.ToString ();
  655. readStringBuffer.Length = 0;
  656. return ret;
  657. }
  658. #if NET_2_0
  659. public virtual Type ValueType {
  660. get { return typeof (string); }
  661. }
  662. public virtual bool ReadToDescendant (string name)
  663. {
  664. if (ReadState == ReadState.Initial) {
  665. MoveToContent ();
  666. if (IsStartElement (name))
  667. return true;
  668. }
  669. if (NodeType != XmlNodeType.Element || IsEmptyElement)
  670. return false;
  671. int depth = Depth;
  672. for (Read (); depth < Depth; Read ())
  673. if (NodeType == XmlNodeType.Element && name == Name)
  674. return true;
  675. return false;
  676. }
  677. public virtual bool ReadToDescendant (string localName, string namespaceURI)
  678. {
  679. if (ReadState == ReadState.Initial) {
  680. MoveToContent ();
  681. if (IsStartElement (localName, namespaceURI))
  682. return true;
  683. }
  684. if (NodeType != XmlNodeType.Element || IsEmptyElement)
  685. return false;
  686. int depth = Depth;
  687. for (Read (); depth < Depth; Read ())
  688. if (NodeType == XmlNodeType.Element && localName == LocalName && namespaceURI == NamespaceURI)
  689. return true;
  690. return false;
  691. }
  692. public virtual bool ReadToFollowing (string name)
  693. {
  694. while (Read ())
  695. if (NodeType == XmlNodeType.Element && name == Name)
  696. return true;
  697. return false;
  698. }
  699. public virtual bool ReadToFollowing (string localName, string namespaceURI)
  700. {
  701. while (Read ())
  702. if (NodeType == XmlNodeType.Element && localName == Name && namespaceURI == NamespaceURI)
  703. return true;
  704. return false;
  705. }
  706. public virtual bool ReadToNextSibling (string name)
  707. {
  708. if (ReadState != ReadState.Interactive)
  709. return false;
  710. int depth = Depth;
  711. for (Skip (); depth >= Depth; Skip ())
  712. if (NodeType == XmlNodeType.Element && name == Name)
  713. return true;
  714. return false;
  715. }
  716. public virtual bool ReadToNextSibling (string localName, string namespaceURI)
  717. {
  718. if (ReadState != ReadState.Interactive)
  719. return false;
  720. int depth = Depth;
  721. for (Skip (); depth >= Depth; Skip ())
  722. if (NodeType == XmlNodeType.Element && localName == LocalName && namespaceURI == NamespaceURI)
  723. return true;
  724. return false;
  725. }
  726. public virtual XmlReader ReadSubtree ()
  727. {
  728. return new SubtreeXmlReader (this);
  729. }
  730. private string ReadContentString ()
  731. {
  732. return ReadContentString (true);
  733. }
  734. private string ReadContentString (bool isText)
  735. {
  736. if (isText) {
  737. switch (NodeType) {
  738. case XmlNodeType.Text:
  739. case XmlNodeType.SignificantWhitespace:
  740. case XmlNodeType.Whitespace:
  741. case XmlNodeType.CDATA:
  742. break;
  743. default:
  744. throw new InvalidOperationException (String.Format ("Node type {0} is not supported in this operation.{1}", NodeType, GetLocation ()));
  745. }
  746. }
  747. string value = String.Empty;
  748. do {
  749. switch (NodeType) {
  750. case XmlNodeType.Element:
  751. if (isText)
  752. return value;
  753. throw XmlError ("Child element is not expected in this operation.");
  754. case XmlNodeType.EndElement:
  755. return value;
  756. case XmlNodeType.Text:
  757. case XmlNodeType.CDATA:
  758. case XmlNodeType.SignificantWhitespace:
  759. case XmlNodeType.Whitespace:
  760. value += Value;
  761. break;
  762. }
  763. } while (Read ());
  764. throw XmlError ("Unexpected end of document.");
  765. }
  766. string GetLocation ()
  767. {
  768. IXmlLineInfo li = this as IXmlLineInfo;
  769. return li != null && li.HasLineInfo () ?
  770. String.Format (" {0} (line {1}, column {2})", BaseURI, li.LineNumber, li.LinePosition) : String.Empty;
  771. }
  772. [MonoTODO]
  773. public virtual object ReadElementContentAsObject ()
  774. {
  775. return ReadElementContentAs (ValueType, null);
  776. }
  777. [MonoTODO]
  778. public virtual object ReadElementContentAsObject (string localName, string namespaceURI)
  779. {
  780. return ReadElementContentAs (ValueType, null, localName, namespaceURI);
  781. }
  782. [MonoTODO]
  783. public virtual object ReadContentAsObject ()
  784. {
  785. return ReadContentAs (ValueType, null);
  786. }
  787. public virtual object ReadElementContentAs (Type type, IXmlNamespaceResolver resolver)
  788. {
  789. bool isEmpty = IsEmptyElement;
  790. ReadStartElement ();
  791. object obj = ValueAs (isEmpty ? String.Empty : ReadContentString (false), type, resolver);
  792. if (!isEmpty)
  793. ReadEndElement ();
  794. return obj;
  795. }
  796. public virtual object ReadElementContentAs (Type type, IXmlNamespaceResolver resolver, string localName, string namespaceURI)
  797. {
  798. ReadStartElement (localName, namespaceURI);
  799. object obj = ReadContentAs (type, resolver);
  800. ReadEndElement ();
  801. return obj;
  802. }
  803. public virtual object ReadContentAs (Type type, IXmlNamespaceResolver resolver)
  804. {
  805. return ValueAs (ReadContentString (), type, resolver);
  806. }
  807. private object ValueAs (string text, Type type, IXmlNamespaceResolver resolver)
  808. {
  809. try {
  810. if (type == typeof (object))
  811. return text;
  812. if (type == typeof (XmlQualifiedName)) {
  813. if (resolver != null)
  814. return XmlQualifiedName.Parse (text, resolver);
  815. else
  816. return XmlQualifiedName.Parse (text, this);
  817. }
  818. switch (Type.GetTypeCode (type)) {
  819. case TypeCode.Boolean:
  820. return XQueryConvert.StringToBoolean (text);
  821. case TypeCode.DateTime:
  822. return XQueryConvert.StringToDateTime (text);
  823. case TypeCode.Decimal:
  824. return XQueryConvert.StringToDecimal (text);
  825. case TypeCode.Double:
  826. return XQueryConvert.StringToDouble (text);
  827. case TypeCode.Int32:
  828. return XQueryConvert.StringToInt (text);
  829. case TypeCode.Int64:
  830. return XQueryConvert.StringToInteger (text);
  831. case TypeCode.Single:
  832. return XQueryConvert.StringToFloat (text);
  833. case TypeCode.String:
  834. return text;
  835. }
  836. } catch (Exception ex) {
  837. 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);
  838. }
  839. throw new ArgumentException (String.Format ("Specified type '{0}' is not supported.", type));
  840. }
  841. public virtual bool ReadElementContentAsBoolean ()
  842. {
  843. try {
  844. return XQueryConvert.StringToBoolean (ReadElementContentAsString ());
  845. } catch (FormatException ex) {
  846. throw XmlError ("Typed value is invalid.", ex);
  847. }
  848. }
  849. public virtual DateTime ReadElementContentAsDateTime ()
  850. {
  851. try {
  852. return XQueryConvert.StringToDateTime (ReadElementContentAsString ());
  853. } catch (FormatException ex) {
  854. throw XmlError ("Typed value is invalid.", ex);
  855. }
  856. }
  857. public virtual decimal ReadElementContentAsDecimal ()
  858. {
  859. try {
  860. return XQueryConvert.StringToDecimal (ReadElementContentAsString ());
  861. } catch (FormatException ex) {
  862. throw XmlError ("Typed value is invalid.", ex);
  863. }
  864. }
  865. public virtual double ReadElementContentAsDouble ()
  866. {
  867. try {
  868. return XQueryConvert.StringToDouble (ReadElementContentAsString ());
  869. } catch (FormatException ex) {
  870. throw XmlError ("Typed value is invalid.", ex);
  871. }
  872. }
  873. public virtual float ReadElementContentAsFloat ()
  874. {
  875. try {
  876. return XQueryConvert.StringToFloat (ReadElementContentAsString ());
  877. } catch (FormatException ex) {
  878. throw XmlError ("Typed value is invalid.", ex);
  879. }
  880. }
  881. public virtual int ReadElementContentAsInt ()
  882. {
  883. try {
  884. return XQueryConvert.StringToInt (ReadElementContentAsString ());
  885. } catch (FormatException ex) {
  886. throw XmlError ("Typed value is invalid.", ex);
  887. }
  888. }
  889. public virtual long ReadElementContentAsLong ()
  890. {
  891. try {
  892. return XQueryConvert.StringToInteger (ReadElementContentAsString ());
  893. } catch (FormatException ex) {
  894. throw XmlError ("Typed value is invalid.", ex);
  895. }
  896. }
  897. public virtual string ReadElementContentAsString ()
  898. {
  899. bool isEmpty = IsEmptyElement;
  900. ReadStartElement ();
  901. if (isEmpty)
  902. return String.Empty;
  903. string s = ReadContentString (false);
  904. ReadEndElement ();
  905. return s;
  906. }
  907. public virtual bool ReadElementContentAsBoolean (string localName, string namespaceURI)
  908. {
  909. try {
  910. return XQueryConvert.StringToBoolean (ReadElementContentAsString (localName, namespaceURI));
  911. } catch (FormatException ex) {
  912. throw XmlError ("Typed value is invalid.", ex);
  913. }
  914. }
  915. public virtual DateTime ReadElementContentAsDateTime (string localName, string namespaceURI)
  916. {
  917. try {
  918. return XQueryConvert.StringToDateTime (ReadElementContentAsString (localName, namespaceURI));
  919. } catch (FormatException ex) {
  920. throw XmlError ("Typed value is invalid.", ex);
  921. }
  922. }
  923. public virtual decimal ReadElementContentAsDecimal (string localName, string namespaceURI)
  924. {
  925. try {
  926. return XQueryConvert.StringToDecimal (ReadElementContentAsString (localName, namespaceURI));
  927. } catch (FormatException ex) {
  928. throw XmlError ("Typed value is invalid.", ex);
  929. }
  930. }
  931. public virtual double ReadElementContentAsDouble (string localName, string namespaceURI)
  932. {
  933. try {
  934. return XQueryConvert.StringToDouble (ReadElementContentAsString (localName, namespaceURI));
  935. } catch (FormatException ex) {
  936. throw XmlError ("Typed value is invalid.", ex);
  937. }
  938. }
  939. public virtual float ReadElementContentAsFloat (string localName, string namespaceURI)
  940. {
  941. try {
  942. return XQueryConvert.StringToFloat (ReadElementContentAsString (localName, namespaceURI));
  943. } catch (FormatException ex) {
  944. throw XmlError ("Typed value is invalid.", ex);
  945. }
  946. }
  947. public virtual int ReadElementContentAsInt (string localName, string namespaceURI)
  948. {
  949. try {
  950. return XQueryConvert.StringToInt (ReadElementContentAsString (localName, namespaceURI));
  951. } catch (FormatException ex) {
  952. throw XmlError ("Typed value is invalid.", ex);
  953. }
  954. }
  955. public virtual long ReadElementContentAsLong (string localName, string namespaceURI)
  956. {
  957. try {
  958. return XQueryConvert.StringToInteger (ReadElementContentAsString (localName, namespaceURI));
  959. } catch (FormatException ex) {
  960. throw XmlError ("Typed value is invalid.", ex);
  961. }
  962. }
  963. public virtual string ReadElementContentAsString (string localName, string namespaceURI)
  964. {
  965. ReadStartElement (localName, namespaceURI);
  966. if (IsEmptyElement)
  967. return String.Empty;
  968. string s = ReadContentString (false);
  969. ReadEndElement ();
  970. return s;
  971. }
  972. public virtual bool ReadContentAsBoolean ()
  973. {
  974. try {
  975. return XQueryConvert.StringToBoolean (ReadContentString ());
  976. } catch (FormatException ex) {
  977. throw XmlError ("Typed value is invalid.", ex);
  978. }
  979. }
  980. public virtual DateTime ReadContentAsDateTime ()
  981. {
  982. try {
  983. return XQueryConvert.StringToDateTime (ReadContentString ());
  984. } catch (FormatException ex) {
  985. throw XmlError ("Typed value is invalid.", ex);
  986. }
  987. }
  988. public virtual decimal ReadContentAsDecimal ()
  989. {
  990. try {
  991. return XQueryConvert.StringToDecimal (ReadContentString ());
  992. } catch (FormatException ex) {
  993. throw XmlError ("Typed value is invalid.", ex);
  994. }
  995. }
  996. public virtual double ReadContentAsDouble ()
  997. {
  998. try {
  999. return XQueryConvert.StringToDouble (ReadContentString ());
  1000. } catch (FormatException ex) {
  1001. throw XmlError ("Typed value is invalid.", ex);
  1002. }
  1003. }
  1004. public virtual float ReadContentAsFloat ()
  1005. {
  1006. try {
  1007. return XQueryConvert.StringToFloat (ReadContentString ());
  1008. } catch (FormatException ex) {
  1009. throw XmlError ("Typed value is invalid.", ex);
  1010. }
  1011. }
  1012. public virtual int ReadContentAsInt ()
  1013. {
  1014. try {
  1015. return XQueryConvert.StringToInt (ReadContentString ());
  1016. } catch (FormatException ex) {
  1017. throw XmlError ("Typed value is invalid.", ex);
  1018. }
  1019. }
  1020. public virtual long ReadContentAsLong ()
  1021. {
  1022. try {
  1023. return XQueryConvert.StringToInteger (ReadContentString ());
  1024. } catch (FormatException ex) {
  1025. throw XmlError ("Typed value is invalid.", ex);
  1026. }
  1027. }
  1028. public virtual string ReadContentAsString ()
  1029. {
  1030. return ReadContentString ();
  1031. }
  1032. public virtual int ReadContentAsBase64 (
  1033. byte [] buffer, int offset, int length)
  1034. {
  1035. CheckSupport ();
  1036. return binary.ReadContentAsBase64 (
  1037. buffer, offset, length);
  1038. }
  1039. public virtual int ReadContentAsBinHex (
  1040. byte [] buffer, int offset, int length)
  1041. {
  1042. CheckSupport ();
  1043. return binary.ReadContentAsBinHex (
  1044. buffer, offset, length);
  1045. }
  1046. public virtual int ReadElementContentAsBase64 (
  1047. byte [] buffer, int offset, int length)
  1048. {
  1049. CheckSupport ();
  1050. return binary.ReadElementContentAsBase64 (
  1051. buffer, offset, length);
  1052. }
  1053. public virtual int ReadElementContentAsBinHex (
  1054. byte [] buffer, int offset, int length)
  1055. {
  1056. CheckSupport ();
  1057. return binary.ReadElementContentAsBinHex (
  1058. buffer, offset, length);
  1059. }
  1060. #endif
  1061. #if NET_2_0
  1062. public virtual int ReadValueChunk (
  1063. char [] buffer, int offset, int length)
  1064. #else
  1065. internal virtual int ReadValueChunk (
  1066. char [] buffer, int offset, int length)
  1067. #endif
  1068. {
  1069. if (!CanReadValueChunk)
  1070. throw new NotSupportedException ();
  1071. if (binary == null)
  1072. binary = new XmlReaderBinarySupport (this);
  1073. return binary.ReadValueChunk (buffer, offset, length);
  1074. }
  1075. private void CheckSupport ()
  1076. {
  1077. // Default implementation expects both.
  1078. if (!CanReadBinaryContent || !CanReadValueChunk)
  1079. throw new NotSupportedException ();
  1080. if (binary == null)
  1081. binary = new XmlReaderBinarySupport (this);
  1082. }
  1083. public abstract void ResolveEntity ();
  1084. public virtual void Skip ()
  1085. {
  1086. if (ReadState != ReadState.Interactive)
  1087. return;
  1088. MoveToElement ();
  1089. if (NodeType != XmlNodeType.Element || IsEmptyElement) {
  1090. Read ();
  1091. return;
  1092. }
  1093. int depth = Depth;
  1094. while (Read () && depth < Depth)
  1095. ;
  1096. if (NodeType == XmlNodeType.EndElement)
  1097. Read ();
  1098. }
  1099. private XmlException XmlError (string message)
  1100. {
  1101. return new XmlException (this as IXmlLineInfo, BaseURI, message);
  1102. }
  1103. private XmlException XmlError (string message, Exception innerException)
  1104. {
  1105. return new XmlException (this as IXmlLineInfo, BaseURI, message);
  1106. }
  1107. #endregion
  1108. }
  1109. }