XmlReader.cs 35 KB

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