XmlReader.cs 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  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; // forced. See XmlReaderCommonTests.CreateFromUrlClose().
  259. return ret;
  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. reader.EntityHandling = EntityHandling.ExpandEntities;
  281. if (settings.ProhibitDtd)
  282. reader.ProhibitDtd = true;
  283. if (!settings.CheckCharacters)
  284. reader.CharacterChecking = false;
  285. // I guess it might be changed in 2.0 RTM to set true
  286. // as default, or just disappear. It goes against
  287. // XmlTextReader's default usage and users will have
  288. // to close input manually (that's annoying). Moreover,
  289. // MS XmlTextReader consumes text input more than
  290. // actually read and users can acquire those extra
  291. // consumption by GetRemainder() that returns different
  292. // TextReader.
  293. reader.CloseInput = settings.CloseInput;
  294. // I would like to support it in detail later;
  295. // MSDN description looks source of confusion. We don't
  296. // need examples, but precise list of how it works.
  297. reader.Conformance = settings.ConformanceLevel;
  298. reader.AdjustLineInfoOffset (settings.LineNumberOffset,
  299. settings.LinePositionOffset);
  300. if (settings.NameTable != null)
  301. reader.SetNameTable (settings.NameTable);
  302. XmlReader r = CreateFilteredXmlReader (reader, settings);
  303. r.settings = settings;
  304. return r;
  305. }
  306. private static XmlReader CreateFilteredXmlReader (XmlReader reader, XmlReaderSettings settings)
  307. {
  308. ConformanceLevel conf = ConformanceLevel.Auto;
  309. if (reader is XmlTextReader)
  310. conf = ((XmlTextReader) reader).Conformance;
  311. else if (reader.Settings != null)
  312. conf = reader.Settings.ConformanceLevel;
  313. else
  314. conf = settings.ConformanceLevel;
  315. if (settings.ConformanceLevel != ConformanceLevel.Auto &&
  316. conf != settings.ConformanceLevel)
  317. 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));
  318. settings.ConformanceLevel = conf;
  319. reader = CreateValidatingXmlReader (reader, settings);
  320. if (reader.Settings != null &&
  321. (settings.IgnoreComments ||
  322. settings.IgnoreProcessingInstructions ||
  323. settings.IgnoreWhitespace))
  324. return new XmlFilterReader (reader, settings);
  325. else {
  326. reader.settings = settings;
  327. return reader;
  328. }
  329. }
  330. private static XmlReader CreateValidatingXmlReader (XmlReader reader, XmlReaderSettings settings)
  331. {
  332. XmlValidatingReader xvr = null;
  333. switch (settings.ValidationType) {
  334. // Auto and XDR are obsoleted in 2.0 and therefore ignored.
  335. default:
  336. return reader;
  337. case ValidationType.DTD:
  338. xvr = new XmlValidatingReader (reader);
  339. xvr.XmlResolver = settings.XmlResolver;
  340. xvr.ValidationType = ValidationType.DTD;
  341. break;
  342. case ValidationType.Schema:
  343. return new XmlSchemaValidatingReader (reader, settings);
  344. }
  345. // Actually I don't think they are treated in DTD validation though...
  346. if ((settings.ValidationFlags & XmlSchemaValidationFlags.ProcessIdentityConstraints) == 0)
  347. throw new NotImplementedException ();
  348. //if ((settings.ValidationFlags & XmlSchemaValidationFlags.ProcessInlineSchema) != 0)
  349. // throw new NotImplementedException ();
  350. //if ((settings.ValidationFlags & XmlSchemaValidationFlags.ProcessSchemaLocation) != 0)
  351. // throw new NotImplementedException ();
  352. //if ((settings.ValidationFlags & XmlSchemaValidationFlags.ReportValidationWarnings) == 0)
  353. // throw new NotImplementedException ();
  354. return xvr != null ? xvr : reader;
  355. }
  356. #endif
  357. #if NET_2_0
  358. void IDisposable.Dispose ()
  359. {
  360. Dispose (false);
  361. }
  362. protected virtual void Dispose (bool disposing)
  363. {
  364. if (ReadState != ReadState.Closed)
  365. Close ();
  366. }
  367. #endif
  368. public abstract string GetAttribute (int i);
  369. public abstract string GetAttribute (string name);
  370. public abstract string GetAttribute (
  371. string localName,
  372. string namespaceName);
  373. public static bool IsName (string s)
  374. {
  375. return s != null && XmlChar.IsName (s);
  376. }
  377. public static bool IsNameToken (string s)
  378. {
  379. return s != null && XmlChar.IsNmToken (s);
  380. }
  381. public virtual bool IsStartElement ()
  382. {
  383. return (MoveToContent () == XmlNodeType.Element);
  384. }
  385. public virtual bool IsStartElement (string name)
  386. {
  387. if (!IsStartElement ())
  388. return false;
  389. return (Name == name);
  390. }
  391. public virtual bool IsStartElement (string localName, string namespaceName)
  392. {
  393. if (!IsStartElement ())
  394. return false;
  395. return (LocalName == localName && NamespaceURI == namespaceName);
  396. }
  397. public abstract string LookupNamespace (string prefix);
  398. #if NET_2_0
  399. public virtual void MoveToAttribute (int i)
  400. {
  401. if (i >= AttributeCount)
  402. throw new ArgumentOutOfRangeException ();
  403. MoveToFirstAttribute ();
  404. for (int a = 0; a < i; a++)
  405. MoveToNextAttribute ();
  406. }
  407. #else
  408. public abstract void MoveToAttribute (int i);
  409. #endif
  410. public abstract bool MoveToAttribute (string name);
  411. public abstract bool MoveToAttribute (
  412. string localName,
  413. string namespaceName);
  414. private bool IsContent (XmlNodeType nodeType)
  415. {
  416. /* MS doc says:
  417. * (non-white space text, CDATA, Element, EndElement, EntityReference, or EndEntity)
  418. */
  419. switch (nodeType) {
  420. case XmlNodeType.Text:
  421. return true;
  422. case XmlNodeType.CDATA:
  423. return true;
  424. case XmlNodeType.Element:
  425. return true;
  426. case XmlNodeType.EndElement:
  427. return true;
  428. case XmlNodeType.EntityReference:
  429. return true;
  430. case XmlNodeType.EndEntity:
  431. return true;
  432. }
  433. return false;
  434. }
  435. public virtual XmlNodeType MoveToContent ()
  436. {
  437. if (NodeType == XmlNodeType.Attribute)
  438. MoveToElement ();
  439. do {
  440. if (IsContent (NodeType))
  441. return NodeType;
  442. Read ();
  443. } while (!EOF);
  444. return XmlNodeType.None;
  445. }
  446. public abstract bool MoveToElement ();
  447. public abstract bool MoveToFirstAttribute ();
  448. public abstract bool MoveToNextAttribute ();
  449. public abstract bool Read ();
  450. public abstract bool ReadAttributeValue ();
  451. public virtual string ReadElementString ()
  452. {
  453. if (MoveToContent () != XmlNodeType.Element) {
  454. string error = String.Format ("'{0}' is an invalid node type.",
  455. NodeType.ToString ());
  456. throw XmlError (error);
  457. }
  458. string result = String.Empty;
  459. if (!IsEmptyElement) {
  460. Read ();
  461. result = ReadString ();
  462. if (NodeType != XmlNodeType.EndElement) {
  463. string error = String.Format ("'{0}' is an invalid node type.",
  464. NodeType.ToString ());
  465. throw XmlError (error);
  466. }
  467. }
  468. Read ();
  469. return result;
  470. }
  471. public virtual string ReadElementString (string name)
  472. {
  473. if (MoveToContent () != XmlNodeType.Element) {
  474. string error = String.Format ("'{0}' is an invalid node type.",
  475. NodeType.ToString ());
  476. throw XmlError (error);
  477. }
  478. if (name != Name) {
  479. string error = String.Format ("The {0} tag from namespace {1} is expected.",
  480. Name, NamespaceURI);
  481. throw XmlError (error);
  482. }
  483. string result = String.Empty;
  484. if (!IsEmptyElement) {
  485. Read ();
  486. result = ReadString ();
  487. if (NodeType != XmlNodeType.EndElement) {
  488. string error = String.Format ("'{0}' is an invalid node type.",
  489. NodeType.ToString ());
  490. throw XmlError (error);
  491. }
  492. }
  493. Read ();
  494. return result;
  495. }
  496. public virtual string ReadElementString (string localName, string namespaceName)
  497. {
  498. if (MoveToContent () != XmlNodeType.Element) {
  499. string error = String.Format ("'{0}' is an invalid node type.",
  500. NodeType.ToString ());
  501. throw XmlError (error);
  502. }
  503. if (localName != LocalName || NamespaceURI != namespaceName) {
  504. string error = String.Format ("The {0} tag from namespace {1} is expected.",
  505. LocalName, NamespaceURI);
  506. throw XmlError (error);
  507. }
  508. string result = String.Empty;
  509. if (!IsEmptyElement) {
  510. Read ();
  511. result = ReadString ();
  512. if (NodeType != XmlNodeType.EndElement) {
  513. string error = String.Format ("'{0}' is an invalid node type.",
  514. NodeType.ToString ());
  515. throw XmlError (error);
  516. }
  517. }
  518. Read ();
  519. return result;
  520. }
  521. public virtual void ReadEndElement ()
  522. {
  523. if (MoveToContent () != XmlNodeType.EndElement) {
  524. string error = String.Format ("'{0}' is an invalid node type.",
  525. NodeType.ToString ());
  526. throw XmlError (error);
  527. }
  528. Read ();
  529. }
  530. public virtual string ReadInnerXml ()
  531. {
  532. if (ReadState != ReadState.Interactive || NodeType == XmlNodeType.EndElement)
  533. return String.Empty;
  534. if (IsEmptyElement) {
  535. Read ();
  536. return String.Empty;
  537. }
  538. StringWriter sw = new StringWriter ();
  539. XmlTextWriter xtw = new XmlTextWriter (sw);
  540. if (NodeType == XmlNodeType.Element) {
  541. int startDepth = Depth;
  542. Read ();
  543. while (startDepth < Depth) {
  544. if (ReadState != ReadState.Interactive)
  545. throw XmlError ("Unexpected end of the XML reader.");
  546. xtw.WriteNode (this, false);
  547. }
  548. // reader is now end element, then proceed once more.
  549. Read ();
  550. }
  551. else
  552. xtw.WriteNode (this, false);
  553. return sw.ToString ();
  554. }
  555. public virtual string ReadOuterXml ()
  556. {
  557. if (ReadState != ReadState.Interactive || NodeType == XmlNodeType.EndElement)
  558. return String.Empty;
  559. switch (NodeType) {
  560. case XmlNodeType.Element:
  561. case XmlNodeType.Attribute:
  562. StringWriter sw = new StringWriter ();
  563. XmlTextWriter xtw = new XmlTextWriter (sw);
  564. xtw.WriteNode (this, false);
  565. return sw.ToString ();
  566. default:
  567. Skip ();
  568. return String.Empty;
  569. }
  570. }
  571. public virtual void ReadStartElement ()
  572. {
  573. if (MoveToContent () != XmlNodeType.Element) {
  574. string error = String.Format ("'{0}' is an invalid node type.",
  575. NodeType.ToString ());
  576. throw XmlError (error);
  577. }
  578. Read ();
  579. }
  580. public virtual void ReadStartElement (string name)
  581. {
  582. if (MoveToContent () != XmlNodeType.Element) {
  583. string error = String.Format ("'{0}' is an invalid node type.",
  584. NodeType.ToString ());
  585. throw XmlError (error);
  586. }
  587. if (name != Name) {
  588. string error = String.Format ("The {0} tag from namespace {1} is expected.",
  589. Name, NamespaceURI);
  590. throw XmlError (error);
  591. }
  592. Read ();
  593. }
  594. public virtual void ReadStartElement (string localName, string namespaceName)
  595. {
  596. if (MoveToContent () != XmlNodeType.Element) {
  597. string error = String.Format ("'{0}' is an invalid node type.",
  598. NodeType.ToString ());
  599. throw XmlError (error);
  600. }
  601. if (localName != LocalName || NamespaceURI != namespaceName) {
  602. string error = String.Format ("Expecting {0} tag from namespace {1}, got {2} and {3} instead",
  603. localName, namespaceName,
  604. LocalName, NamespaceURI);
  605. throw XmlError (error);
  606. }
  607. Read ();
  608. }
  609. public virtual string ReadString ()
  610. {
  611. if (readStringBuffer == null)
  612. readStringBuffer = new StringBuilder ();
  613. readStringBuffer.Length = 0;
  614. MoveToElement ();
  615. switch (NodeType) {
  616. default:
  617. return String.Empty;
  618. case XmlNodeType.Element:
  619. if (IsEmptyElement)
  620. return String.Empty;
  621. do {
  622. Read ();
  623. switch (NodeType) {
  624. case XmlNodeType.Text:
  625. case XmlNodeType.CDATA:
  626. case XmlNodeType.Whitespace:
  627. case XmlNodeType.SignificantWhitespace:
  628. readStringBuffer.Append (Value);
  629. continue;
  630. }
  631. break;
  632. } while (true);
  633. break;
  634. case XmlNodeType.Text:
  635. case XmlNodeType.CDATA:
  636. case XmlNodeType.Whitespace:
  637. case XmlNodeType.SignificantWhitespace:
  638. do {
  639. switch (NodeType) {
  640. case XmlNodeType.Text:
  641. case XmlNodeType.CDATA:
  642. case XmlNodeType.Whitespace:
  643. case XmlNodeType.SignificantWhitespace:
  644. readStringBuffer.Append (Value);
  645. Read ();
  646. continue;
  647. }
  648. break;
  649. } while (true);
  650. break;
  651. }
  652. string ret = readStringBuffer.ToString ();
  653. readStringBuffer.Length = 0;
  654. return ret;
  655. }
  656. #if NET_2_0
  657. public virtual Type ValueType {
  658. get { return typeof (string); }
  659. }
  660. public virtual bool ReadToDescendant (string name)
  661. {
  662. if (ReadState == ReadState.Initial) {
  663. MoveToContent ();
  664. if (IsStartElement (name))
  665. return true;
  666. }
  667. if (NodeType != XmlNodeType.Element || IsEmptyElement)
  668. return false;
  669. int depth = Depth;
  670. for (Read (); depth < Depth; Read ())
  671. if (NodeType == XmlNodeType.Element && name == Name)
  672. return true;
  673. return false;
  674. }
  675. public virtual bool ReadToDescendant (string localName, string namespaceURI)
  676. {
  677. if (ReadState == ReadState.Initial) {
  678. MoveToContent ();
  679. if (IsStartElement (localName, namespaceURI))
  680. return true;
  681. }
  682. if (NodeType != XmlNodeType.Element || IsEmptyElement)
  683. return false;
  684. int depth = Depth;
  685. for (Read (); depth < Depth; Read ())
  686. if (NodeType == XmlNodeType.Element && localName == LocalName && namespaceURI == NamespaceURI)
  687. return true;
  688. return false;
  689. }
  690. public virtual bool ReadToFollowing (string name)
  691. {
  692. while (Read ())
  693. if (NodeType == XmlNodeType.Element && name == Name)
  694. return true;
  695. return false;
  696. }
  697. public virtual bool ReadToFollowing (string localName, string namespaceURI)
  698. {
  699. while (Read ())
  700. if (NodeType == XmlNodeType.Element && localName == Name && namespaceURI == NamespaceURI)
  701. return true;
  702. return false;
  703. }
  704. public virtual bool ReadToNextSibling (string name)
  705. {
  706. if (ReadState != ReadState.Interactive)
  707. return false;
  708. int depth = Depth;
  709. for (Skip (); depth >= Depth; Skip ())
  710. if (NodeType == XmlNodeType.Element && name == Name)
  711. return true;
  712. return false;
  713. }
  714. public virtual bool ReadToNextSibling (string localName, string namespaceURI)
  715. {
  716. if (ReadState != ReadState.Interactive)
  717. return false;
  718. int depth = Depth;
  719. for (Skip (); depth >= Depth; Skip ())
  720. if (NodeType == XmlNodeType.Element && localName == LocalName && namespaceURI == NamespaceURI)
  721. return true;
  722. return false;
  723. }
  724. public virtual XmlReader ReadSubtree ()
  725. {
  726. return new SubtreeXmlReader (this);
  727. }
  728. private string ReadContentString ()
  729. {
  730. if (NodeType == XmlNodeType.Attribute)
  731. return Value;
  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. bool isEmpty = IsEmptyElement;
  966. ReadStartElement (localName, namespaceURI);
  967. if (isEmpty)
  968. return String.Empty;
  969. string s = ReadContentString (false);
  970. ReadEndElement ();
  971. return s;
  972. }
  973. public virtual bool ReadContentAsBoolean ()
  974. {
  975. try {
  976. return XQueryConvert.StringToBoolean (ReadContentString ());
  977. } catch (FormatException ex) {
  978. throw XmlError ("Typed value is invalid.", ex);
  979. }
  980. }
  981. public virtual DateTime ReadContentAsDateTime ()
  982. {
  983. try {
  984. return XQueryConvert.StringToDateTime (ReadContentString ());
  985. } catch (FormatException ex) {
  986. throw XmlError ("Typed value is invalid.", ex);
  987. }
  988. }
  989. public virtual decimal ReadContentAsDecimal ()
  990. {
  991. try {
  992. return XQueryConvert.StringToDecimal (ReadContentString ());
  993. } catch (FormatException ex) {
  994. throw XmlError ("Typed value is invalid.", ex);
  995. }
  996. }
  997. public virtual double ReadContentAsDouble ()
  998. {
  999. try {
  1000. return XQueryConvert.StringToDouble (ReadContentString ());
  1001. } catch (FormatException ex) {
  1002. throw XmlError ("Typed value is invalid.", ex);
  1003. }
  1004. }
  1005. public virtual float ReadContentAsFloat ()
  1006. {
  1007. try {
  1008. return XQueryConvert.StringToFloat (ReadContentString ());
  1009. } catch (FormatException ex) {
  1010. throw XmlError ("Typed value is invalid.", ex);
  1011. }
  1012. }
  1013. public virtual int ReadContentAsInt ()
  1014. {
  1015. try {
  1016. return XQueryConvert.StringToInt (ReadContentString ());
  1017. } catch (FormatException ex) {
  1018. throw XmlError ("Typed value is invalid.", ex);
  1019. }
  1020. }
  1021. public virtual long ReadContentAsLong ()
  1022. {
  1023. try {
  1024. return XQueryConvert.StringToInteger (ReadContentString ());
  1025. } catch (FormatException ex) {
  1026. throw XmlError ("Typed value is invalid.", ex);
  1027. }
  1028. }
  1029. public virtual string ReadContentAsString ()
  1030. {
  1031. return ReadContentString ();
  1032. }
  1033. public virtual int ReadContentAsBase64 (
  1034. byte [] buffer, int offset, int length)
  1035. {
  1036. CheckSupport ();
  1037. return binary.ReadContentAsBase64 (
  1038. buffer, offset, length);
  1039. }
  1040. public virtual int ReadContentAsBinHex (
  1041. byte [] buffer, int offset, int length)
  1042. {
  1043. CheckSupport ();
  1044. return binary.ReadContentAsBinHex (
  1045. buffer, offset, length);
  1046. }
  1047. public virtual int ReadElementContentAsBase64 (
  1048. byte [] buffer, int offset, int length)
  1049. {
  1050. CheckSupport ();
  1051. return binary.ReadElementContentAsBase64 (
  1052. buffer, offset, length);
  1053. }
  1054. public virtual int ReadElementContentAsBinHex (
  1055. byte [] buffer, int offset, int length)
  1056. {
  1057. CheckSupport ();
  1058. return binary.ReadElementContentAsBinHex (
  1059. buffer, offset, length);
  1060. }
  1061. #endif
  1062. #if NET_2_0
  1063. public virtual int ReadValueChunk (
  1064. char [] buffer, int offset, int length)
  1065. #else
  1066. internal virtual int ReadValueChunk (
  1067. char [] buffer, int offset, int length)
  1068. #endif
  1069. {
  1070. if (!CanReadValueChunk)
  1071. throw new NotSupportedException ();
  1072. if (binary == null)
  1073. binary = new XmlReaderBinarySupport (this);
  1074. return binary.ReadValueChunk (buffer, offset, length);
  1075. }
  1076. private void CheckSupport ()
  1077. {
  1078. // Default implementation expects both.
  1079. if (!CanReadBinaryContent || !CanReadValueChunk)
  1080. throw new NotSupportedException ();
  1081. if (binary == null)
  1082. binary = new XmlReaderBinarySupport (this);
  1083. }
  1084. public abstract void ResolveEntity ();
  1085. public virtual void Skip ()
  1086. {
  1087. if (ReadState != ReadState.Interactive)
  1088. return;
  1089. MoveToElement ();
  1090. if (NodeType != XmlNodeType.Element || IsEmptyElement) {
  1091. Read ();
  1092. return;
  1093. }
  1094. int depth = Depth;
  1095. while (Read () && depth < Depth)
  1096. ;
  1097. if (NodeType == XmlNodeType.EndElement)
  1098. Read ();
  1099. }
  1100. private XmlException XmlError (string message)
  1101. {
  1102. return new XmlException (this as IXmlLineInfo, BaseURI, message);
  1103. }
  1104. private XmlException XmlError (string message, Exception innerException)
  1105. {
  1106. return new XmlException (this as IXmlLineInfo, BaseURI, message);
  1107. }
  1108. #endregion
  1109. }
  1110. }