XmlWriter.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. //
  2. // System.Xml.XmlWriter
  3. //
  4. // Authors:
  5. // Kral Ferch <[email protected]>
  6. // Atsushi Enomoto <[email protected]>
  7. //
  8. // (C) 2002 Kral Ferch
  9. // (C) 2002-2003 Atsushi Enomoto
  10. //
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System;
  32. using System.IO;
  33. using System.Text;
  34. #if NET_2_0
  35. using System.Xml.XPath;
  36. #endif
  37. namespace System.Xml
  38. {
  39. #if NET_2_0
  40. public abstract class XmlWriter : IDisposable
  41. #else
  42. public abstract class XmlWriter
  43. #endif
  44. {
  45. #if NET_2_0
  46. XmlWriterSettings settings;
  47. #endif
  48. #region Constructors
  49. protected XmlWriter () { }
  50. #endregion
  51. #region Properties
  52. #if NET_2_0
  53. public virtual XmlWriterSettings Settings {
  54. get {
  55. if (settings == null)
  56. settings = new XmlWriterSettings ();
  57. return settings;
  58. }
  59. }
  60. #endif
  61. public abstract WriteState WriteState { get; }
  62. #if NET_2_0
  63. public virtual string XmlLang {
  64. get { return null; }
  65. }
  66. public virtual XmlSpace XmlSpace {
  67. get { return XmlSpace.None; }
  68. }
  69. #else
  70. public abstract string XmlLang { get; }
  71. public abstract XmlSpace XmlSpace { get; }
  72. #endif
  73. #endregion
  74. #region Methods
  75. public abstract void Close ();
  76. #if NET_2_0
  77. public static XmlWriter Create (Stream stream)
  78. {
  79. return Create (stream, null);
  80. }
  81. public static XmlWriter Create (string file)
  82. {
  83. return Create (file, null);
  84. }
  85. public static XmlWriter Create (TextWriter writer)
  86. {
  87. return Create (writer, null);
  88. }
  89. public static XmlWriter Create (XmlWriter writer)
  90. {
  91. return Create (writer, null);
  92. }
  93. public static XmlWriter Create (StringBuilder builder)
  94. {
  95. return Create (builder, null);
  96. }
  97. public static XmlWriter Create (Stream stream, XmlWriterSettings settings)
  98. {
  99. Encoding enc = settings != null ? settings.Encoding : Encoding.UTF8;
  100. return Create (new StreamWriter (stream, enc), settings);
  101. }
  102. public static XmlWriter Create (string file, XmlWriterSettings settings)
  103. {
  104. Encoding enc = settings != null ? settings.Encoding : Encoding.UTF8;
  105. return CreateTextWriter (new StreamWriter (file, false, enc), settings, true);
  106. }
  107. public static XmlWriter Create (StringBuilder builder, XmlWriterSettings settings)
  108. {
  109. return Create (new StringWriter (builder), settings);
  110. }
  111. public static XmlWriter Create (TextWriter writer, XmlWriterSettings settings)
  112. {
  113. if (settings == null)
  114. settings = new XmlWriterSettings ();
  115. return CreateTextWriter (writer, settings, settings.CloseOutput);
  116. }
  117. public static XmlWriter Create (XmlWriter writer, XmlWriterSettings settings)
  118. {
  119. if (settings == null)
  120. settings = new XmlWriterSettings ();
  121. writer.settings = settings;
  122. return writer;
  123. }
  124. private static XmlWriter CreateTextWriter (TextWriter writer, XmlWriterSettings settings, bool closeOutput)
  125. {
  126. if (settings == null)
  127. settings = new XmlWriterSettings ();
  128. XmlTextWriter xtw = new XmlTextWriter (writer, settings, closeOutput);
  129. return Create (xtw, settings);
  130. }
  131. protected virtual void Dispose (bool disposing)
  132. {
  133. Close ();
  134. }
  135. void IDisposable.Dispose ()
  136. {
  137. Dispose (false);
  138. }
  139. #endif
  140. public abstract void Flush ();
  141. public abstract string LookupPrefix (string ns);
  142. private void WriteAttribute (XmlReader reader, bool defattr)
  143. {
  144. if (!defattr && reader.IsDefault)
  145. return;
  146. WriteStartAttribute (reader.Prefix, reader.LocalName, reader.NamespaceURI);
  147. while (reader.ReadAttributeValue ()) {
  148. switch (reader.NodeType) {
  149. case XmlNodeType.Text:
  150. WriteString (reader.Value);
  151. break;
  152. case XmlNodeType.EntityReference:
  153. WriteEntityRef (reader.Name);
  154. break;
  155. }
  156. }
  157. WriteEndAttribute ();
  158. }
  159. public virtual void WriteAttributes (XmlReader reader, bool defattr)
  160. {
  161. if(reader == null)
  162. throw new ArgumentException("null XmlReader specified.", "reader");
  163. switch (reader.NodeType) {
  164. case XmlNodeType.XmlDeclaration:
  165. WriteAttributeString ("version", reader ["version"]);
  166. if (reader ["encoding"] != null)
  167. WriteAttributeString ("encoding", reader ["encoding"]);
  168. if (reader ["standalone"] != null)
  169. WriteAttributeString ("standalone", reader ["standalone"]);
  170. break;
  171. case XmlNodeType.Element:
  172. if (reader.MoveToFirstAttribute ())
  173. goto case XmlNodeType.Attribute;
  174. break;
  175. case XmlNodeType.Attribute:
  176. do {
  177. WriteAttribute (reader, defattr);
  178. } while (reader.MoveToNextAttribute ());
  179. reader.MoveToElement ();
  180. break;
  181. default:
  182. throw new XmlException("NodeType is not one of Element, Attribute, nor XmlDeclaration.");
  183. }
  184. }
  185. public void WriteAttributeString (string localName, string value)
  186. {
  187. WriteAttributeString ("", localName, null, value);
  188. }
  189. public void WriteAttributeString (string localName, string ns, string value)
  190. {
  191. WriteAttributeString ("", localName, ns, value);
  192. }
  193. public void WriteAttributeString (string prefix, string localName, string ns, string value)
  194. {
  195. // In MS.NET (1.0), this check is done *here*, not at WriteStartAttribute.
  196. // (XmlTextWriter.WriteStartAttribute("xmlns", "anyname", null) throws an exception.
  197. WriteStartAttribute (prefix, localName, ns);
  198. if (value != null && value.Length > 0)
  199. WriteString (value);
  200. WriteEndAttribute ();
  201. }
  202. public abstract void WriteBase64 (byte[] buffer, int index, int count);
  203. #if NET_2_0
  204. public virtual void WriteBinHex (byte [] buffer, int index, int count)
  205. {
  206. StringWriter sw = new StringWriter ();
  207. XmlConvert.WriteBinHex (buffer, index, count, sw);
  208. WriteString (sw.ToString ());
  209. }
  210. #else
  211. public abstract void WriteBinHex (byte[] buffer, int index, int count);
  212. #endif
  213. public abstract void WriteCData (string text);
  214. public abstract void WriteCharEntity (char ch);
  215. public abstract void WriteChars (char[] buffer, int index, int count);
  216. public abstract void WriteComment (string text);
  217. public abstract void WriteDocType (string name, string pubid, string sysid, string subset);
  218. public void WriteElementString (string localName, string value)
  219. {
  220. WriteStartElement(localName);
  221. if (value != null && value.Length > 0)
  222. WriteString(value);
  223. WriteEndElement();
  224. }
  225. public void WriteElementString (string localName, string ns, string value)
  226. {
  227. WriteStartElement(localName, ns);
  228. if (value != null && value.Length > 0)
  229. WriteString(value);
  230. WriteEndElement();
  231. }
  232. #if NET_2_0
  233. public void WriteElementString (string prefix, string localName, string ns, string value)
  234. {
  235. WriteStartElement(prefix, localName, ns);
  236. if (value != null && value.Length > 0)
  237. WriteString(value);
  238. WriteEndElement();
  239. }
  240. #endif
  241. public abstract void WriteEndAttribute ();
  242. public abstract void WriteEndDocument ();
  243. public abstract void WriteEndElement ();
  244. public abstract void WriteEntityRef (string name);
  245. public abstract void WriteFullEndElement ();
  246. #if NET_2_0
  247. public virtual void WriteName (string name)
  248. {
  249. WriteNameInternal (name);
  250. }
  251. public virtual void WriteNmToken (string name)
  252. {
  253. WriteNmTokenInternal (name);
  254. }
  255. public virtual void WriteQualifiedName (string localName, string ns)
  256. {
  257. WriteQualifiedNameInternal (localName, ns);
  258. }
  259. #else
  260. public abstract void WriteName (string name);
  261. public abstract void WriteNmToken (string name);
  262. public abstract void WriteQualifiedName (string localName, string ns);
  263. #endif
  264. internal void WriteNameInternal (string name)
  265. {
  266. #if NET_2_0
  267. switch (Settings.ConformanceLevel) {
  268. case ConformanceLevel.Document:
  269. case ConformanceLevel.Fragment:
  270. XmlConvert.VerifyName (name);
  271. break;
  272. }
  273. #else
  274. XmlConvert.VerifyName (name);
  275. #endif
  276. WriteString (name);
  277. }
  278. internal virtual void WriteNmTokenInternal (string name)
  279. {
  280. bool valid = true;
  281. #if NET_2_0
  282. switch (Settings.ConformanceLevel) {
  283. case ConformanceLevel.Document:
  284. case ConformanceLevel.Fragment:
  285. valid = XmlChar.IsNmToken (name);
  286. break;
  287. }
  288. #else
  289. valid = XmlChar.IsNmToken (name);
  290. #endif
  291. if (!valid)
  292. throw new ArgumentException ("Argument name is not a valid NMTOKEN.");
  293. WriteString (name);
  294. }
  295. internal void WriteQualifiedNameInternal (string localName, string ns)
  296. {
  297. if (localName == null || localName == String.Empty)
  298. throw new ArgumentException ();
  299. if (ns == null)
  300. ns = String.Empty;
  301. #if NET_2_0
  302. switch (Settings.ConformanceLevel) {
  303. case ConformanceLevel.Document:
  304. case ConformanceLevel.Fragment:
  305. XmlConvert.VerifyNCName (localName);
  306. break;
  307. }
  308. #else
  309. XmlConvert.VerifyNCName (localName);
  310. #endif
  311. string prefix = ns.Length > 0 ? LookupPrefix (ns) : String.Empty;
  312. if (prefix == null)
  313. throw new ArgumentException (String.Format ("Namespace '{0}' is not declared.", ns));
  314. if (prefix != String.Empty) {
  315. WriteString (prefix);
  316. WriteString (":");
  317. WriteString (localName);
  318. }
  319. else
  320. WriteString (localName);
  321. }
  322. #if NET_2_0
  323. [MonoTODO] // FIXME: test defattr handling
  324. public virtual void WriteNode (XPathNavigator navigator, bool defattr)
  325. {
  326. if (navigator == null)
  327. throw new ArgumentNullException ("navigator");
  328. switch (navigator.NodeType) {
  329. case XPathNodeType.Attribute:
  330. case XPathNodeType.Namespace:
  331. if (defattr || navigator.SchemaInfo == null ||
  332. !navigator.SchemaInfo.IsDefault)
  333. WriteAttributeString (navigator.Prefix,
  334. navigator.LocalName,
  335. navigator.NamespaceURI,
  336. navigator.Value);
  337. break;
  338. case XPathNodeType.Text:
  339. WriteString (navigator.Value);
  340. break;
  341. case XPathNodeType.SignificantWhitespace:
  342. WriteWhitespace (navigator.Value);
  343. break;
  344. case XPathNodeType.Whitespace:
  345. WriteWhitespace (navigator.Value);
  346. break;
  347. case XPathNodeType.Comment:
  348. WriteComment (navigator.Value);
  349. break;
  350. case XPathNodeType.ProcessingInstruction:
  351. WriteProcessingInstruction (navigator.Name, navigator.Value);
  352. break;
  353. case XPathNodeType.Root:
  354. if (navigator.MoveToFirstChild ()) {
  355. do {
  356. WriteNode (navigator, defattr);
  357. } while (navigator.MoveToNext ());
  358. navigator.MoveToParent ();
  359. }
  360. break;
  361. case XPathNodeType.Element:
  362. WriteStartElement (navigator.Prefix, navigator.LocalName, navigator.NamespaceURI);
  363. if (navigator.MoveToFirstNamespace (XPathNamespaceScope.Local)) {
  364. do {
  365. WriteNode (navigator, defattr);
  366. } while (navigator.MoveToNextNamespace (XPathNamespaceScope.Local));
  367. navigator.MoveToParent ();
  368. }
  369. if (navigator.MoveToFirstAttribute ()) {
  370. do {
  371. WriteNode (navigator, defattr);
  372. } while (navigator.MoveToNextAttribute ());
  373. navigator.MoveToParent ();
  374. }
  375. if (navigator.MoveToFirstChild ()) {
  376. do {
  377. WriteNode (navigator, defattr);
  378. } while (navigator.MoveToNext ());
  379. navigator.MoveToParent ();
  380. }
  381. if (navigator.IsEmptyElement)
  382. WriteEndElement ();
  383. else
  384. WriteFullEndElement ();
  385. break;
  386. default:
  387. throw new NotSupportedException ();
  388. }
  389. }
  390. #endif
  391. public virtual void WriteNode (XmlReader reader, bool defattr)
  392. {
  393. if (reader == null)
  394. throw new ArgumentException ();
  395. if (reader.ReadState == ReadState.Initial) {
  396. reader.Read ();
  397. do {
  398. WriteNode (reader, defattr);
  399. } while (!reader.EOF);
  400. return;
  401. }
  402. switch (reader.NodeType) {
  403. case XmlNodeType.Element:
  404. WriteStartElement (reader.Prefix, reader.LocalName, reader.NamespaceURI);
  405. #if false
  406. WriteAttributes (reader, defattr);
  407. reader.MoveToElement ();
  408. #else
  409. // Well, I found that MS.NET took this way, since
  410. // there was a error-prone SgmlReader that fails
  411. // MoveToNextAttribute().
  412. if (reader.HasAttributes) {
  413. for (int i = 0; i < reader.AttributeCount; i++) {
  414. reader.MoveToAttribute (i);
  415. WriteAttribute (reader, defattr);
  416. }
  417. reader.MoveToElement ();
  418. }
  419. #endif
  420. if (reader.IsEmptyElement)
  421. WriteEndElement ();
  422. else {
  423. int depth = reader.Depth;
  424. reader.Read ();
  425. if (reader.NodeType != XmlNodeType.EndElement) {
  426. do {
  427. WriteNode (reader, defattr);
  428. } while (depth < reader.Depth);
  429. }
  430. WriteFullEndElement ();
  431. }
  432. break;
  433. // In case of XmlAttribute, don't proceed reader, and it will never be written.
  434. case XmlNodeType.Attribute:
  435. return;
  436. case XmlNodeType.Text:
  437. WriteString (reader.Value);
  438. break;
  439. case XmlNodeType.CDATA:
  440. WriteCData (reader.Value);
  441. break;
  442. case XmlNodeType.EntityReference:
  443. WriteEntityRef (reader.Name);
  444. break;
  445. case XmlNodeType.XmlDeclaration:
  446. // LAMESPEC: It means that XmlWriter implementation _must not_ check
  447. // whether PI name is "xml" (it is XML error) or not.
  448. case XmlNodeType.ProcessingInstruction:
  449. WriteProcessingInstruction (reader.Name, reader.Value);
  450. break;
  451. case XmlNodeType.Comment:
  452. WriteComment (reader.Value);
  453. break;
  454. case XmlNodeType.DocumentType:
  455. WriteDocType (reader.Name,
  456. reader ["PUBLIC"], reader ["SYSTEM"], reader.Value);
  457. break;
  458. case XmlNodeType.SignificantWhitespace:
  459. goto case XmlNodeType.Whitespace;
  460. case XmlNodeType.Whitespace:
  461. WriteWhitespace (reader.Value);
  462. break;
  463. case XmlNodeType.EndElement:
  464. WriteFullEndElement ();
  465. break;
  466. case XmlNodeType.EndEntity:
  467. break;
  468. case XmlNodeType.None:
  469. break; // Do nothing, nor reporting errors.
  470. default:
  471. throw new XmlException ("Unexpected node " + reader.Name + " of type " + reader.NodeType);
  472. }
  473. reader.Read ();
  474. }
  475. public abstract void WriteProcessingInstruction (string name, string text);
  476. public abstract void WriteRaw (string data);
  477. public abstract void WriteRaw (char[] buffer, int index, int count);
  478. #if NET_2_0
  479. public void WriteStartAttribute (string localName)
  480. {
  481. WriteStartAttribute (null, localName, null);
  482. }
  483. #endif
  484. public void WriteStartAttribute (string localName, string ns)
  485. {
  486. WriteStartAttribute (null, localName, ns);
  487. }
  488. public abstract void WriteStartAttribute (string prefix, string localName, string ns);
  489. public abstract void WriteStartDocument ();
  490. public abstract void WriteStartDocument (bool standalone);
  491. public void WriteStartElement (string localName)
  492. {
  493. WriteStartElement (null, localName, null);
  494. }
  495. public void WriteStartElement (string localName, string ns)
  496. {
  497. WriteStartElement (null, localName, ns);
  498. }
  499. public abstract void WriteStartElement (string prefix, string localName, string ns);
  500. public abstract void WriteString (string text);
  501. public abstract void WriteSurrogateCharEntity (char lowChar, char highChar);
  502. public abstract void WriteWhitespace (string ws);
  503. #if NET_2_0
  504. [MonoTODO]
  505. public virtual void WriteValue (bool value)
  506. {
  507. WriteString (XQueryConvert.BooleanToString (value));
  508. }
  509. [MonoTODO]
  510. public virtual void WriteValue (DateTime value)
  511. {
  512. WriteString (XmlConvert.ToString (value));
  513. }
  514. [MonoTODO]
  515. public virtual void WriteValue (decimal value)
  516. {
  517. WriteString (XQueryConvert.DecimalToString (value));
  518. }
  519. [MonoTODO]
  520. public virtual void WriteValue (double value)
  521. {
  522. WriteString (XQueryConvert.DoubleToString (value));
  523. }
  524. [MonoTODO]
  525. public virtual void WriteValue (int value)
  526. {
  527. WriteString (XQueryConvert.IntToString (value));
  528. }
  529. [MonoTODO]
  530. public virtual void WriteValue (long value)
  531. {
  532. WriteString (XQueryConvert.IntegerToString (value));
  533. }
  534. [MonoTODO]
  535. public virtual void WriteValue (object value)
  536. {
  537. if (value is string)
  538. WriteString ((string) value);
  539. else if (value is bool)
  540. WriteValue ((bool) value);
  541. else if (value is DateTime)
  542. WriteValue ((DateTime) value);
  543. else if (value is decimal)
  544. WriteValue ((decimal) value);
  545. else if (value is double)
  546. WriteValue ((double) value);
  547. else if (value is int)
  548. WriteValue ((int) value);
  549. else if (value is long)
  550. WriteValue ((long) value);
  551. else if (value is XmlQualifiedName) {
  552. XmlQualifiedName qname = (XmlQualifiedName) value;
  553. WriteQualifiedName (qname.Name, qname.Namespace);
  554. }
  555. else
  556. throw new NotImplementedException ("Argument value is " + value);
  557. }
  558. [MonoTODO]
  559. public virtual void WriteValue (float value)
  560. {
  561. WriteString (XQueryConvert.FloatToString (value));
  562. }
  563. [MonoTODO]
  564. public virtual void WriteValue (string value)
  565. {
  566. WriteString (value);
  567. }
  568. #endif
  569. #endregion
  570. }
  571. }