XmlReader.cs 35 KB

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