XmlWriter.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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. [MonoTODO ("NewLineHandling/OutputMethod")]
  98. public static XmlWriter Create (Stream stream, XmlWriterSettings settings)
  99. {
  100. // FIXME: this might result in encoding null reference
  101. Encoding enc = settings != null ? settings.Encoding : Encoding.UTF8;
  102. return Create (new StreamWriter (stream, enc), settings);
  103. }
  104. [MonoTODO ("NewLineHandling/OutputMethod")]
  105. public static XmlWriter Create (string file, XmlWriterSettings settings)
  106. {
  107. // FIXME: this might result in encoding null reference
  108. Encoding enc = settings != null ? settings.Encoding : Encoding.UTF8;
  109. return Create (new StreamWriter (file, false, enc), settings);
  110. }
  111. [MonoTODO ("NewLineHandling/OutputMethod")]
  112. public static XmlWriter Create (StringBuilder builder, XmlWriterSettings settings)
  113. {
  114. return Create (new StringWriter (builder), null);
  115. }
  116. [MonoTODO ("NewLineHandling/OutputMethod")]
  117. public static XmlWriter Create (TextWriter writer, XmlWriterSettings settings)
  118. {
  119. return CreateTextWriter (writer, settings);
  120. }
  121. [MonoTODO ("NewLineHandling/OutputMethod")]
  122. public static XmlWriter Create (XmlWriter writer, XmlWriterSettings settings)
  123. {
  124. if (settings == null)
  125. settings = new XmlWriterSettings ();
  126. writer.settings = settings;
  127. return writer;
  128. }
  129. private static XmlWriter CreateTextWriter (TextWriter writer, XmlWriterSettings settings)
  130. {
  131. if (settings == null)
  132. settings = new XmlWriterSettings ();
  133. XmlTextWriter xtw = new XmlTextWriter (writer);
  134. // Indent, IndentChars
  135. if (settings.Indent) {
  136. xtw.Formatting = Formatting.Indented;
  137. xtw.IndentChars = settings.IndentChars;
  138. xtw.NewLineOnAttributes = settings.NewLineOnAttributes;
  139. }
  140. // NewLineChars
  141. xtw.NewLineChars = settings.NewLineChars;
  142. // CloseOutput
  143. xtw.CloseOutput = settings.CloseOutput;
  144. // ConformanceLevel
  145. xtw.ConformanceLevel = settings.ConformanceLevel;
  146. // OmitXmlDeclaration
  147. xtw.OmitXmlDeclaration = settings.OmitXmlDeclaration;
  148. // CheckCharacters
  149. xtw.CheckCharacters = settings.CheckCharacters;
  150. return Create (xtw, settings);
  151. }
  152. public virtual void Dispose (bool disposing)
  153. {
  154. Close ();
  155. }
  156. void IDisposable.Dispose ()
  157. {
  158. Dispose (false);
  159. }
  160. #endif
  161. public abstract void Flush ();
  162. public abstract string LookupPrefix (string ns);
  163. private void WriteAttribute (XmlReader reader, bool defattr)
  164. {
  165. if (!defattr && reader.IsDefault)
  166. return;
  167. WriteStartAttribute (reader.Prefix, reader.LocalName, reader.NamespaceURI);
  168. while (reader.ReadAttributeValue ()) {
  169. switch (reader.NodeType) {
  170. case XmlNodeType.Text:
  171. WriteString (reader.Value);
  172. break;
  173. case XmlNodeType.EntityReference:
  174. WriteEntityRef (reader.Name);
  175. break;
  176. }
  177. }
  178. WriteEndAttribute ();
  179. }
  180. public virtual void WriteAttributes (XmlReader reader, bool defattr)
  181. {
  182. if(reader == null)
  183. throw new ArgumentException("null XmlReader specified.", "reader");
  184. switch (reader.NodeType) {
  185. case XmlNodeType.XmlDeclaration:
  186. WriteAttributeString ("version", reader ["version"]);
  187. if (reader ["encoding"] != null)
  188. WriteAttributeString ("encoding", reader ["encoding"]);
  189. if (reader ["standalone"] != null)
  190. WriteAttributeString ("standalone", reader ["standalone"]);
  191. break;
  192. case XmlNodeType.Element:
  193. if (reader.MoveToFirstAttribute ())
  194. goto case XmlNodeType.Attribute;
  195. break;
  196. case XmlNodeType.Attribute:
  197. do {
  198. WriteAttribute (reader, defattr);
  199. } while (reader.MoveToNextAttribute ());
  200. reader.MoveToElement ();
  201. break;
  202. default:
  203. throw new XmlException("NodeType is not one of Element, Attribute, nor XmlDeclaration.");
  204. }
  205. }
  206. public void WriteAttributeString (string localName, string value)
  207. {
  208. WriteAttributeString ("", localName, null, value);
  209. }
  210. public void WriteAttributeString (string localName, string ns, string value)
  211. {
  212. WriteAttributeString ("", localName, ns, value);
  213. }
  214. public void WriteAttributeString (string prefix, string localName, string ns, string value)
  215. {
  216. // In MS.NET (1.0), this check is done *here*, not at WriteStartAttribute.
  217. // (XmlTextWriter.WriteStartAttribute("xmlns", "anyname", null) throws an exception.
  218. #if NET_1_0
  219. if ((prefix == "xmlns" || (prefix == "" && localName == "xmlns")) && ns == null)
  220. ns = "http://www.w3.org/2000/xmlns/";
  221. #endif
  222. WriteStartAttribute (prefix, localName, ns);
  223. WriteString (value);
  224. WriteEndAttribute ();
  225. }
  226. public abstract void WriteBase64 (byte[] buffer, int index, int count);
  227. #if NET_2_0
  228. public virtual void WriteBinHex (byte [] buffer, int index, int count)
  229. {
  230. StringWriter sw = new StringWriter ();
  231. XmlConvert.WriteBinHex (buffer, index, count, sw);
  232. WriteString (sw.ToString ());
  233. }
  234. #else
  235. public abstract void WriteBinHex (byte[] buffer, int index, int count);
  236. #endif
  237. public abstract void WriteCData (string text);
  238. public abstract void WriteCharEntity (char ch);
  239. public abstract void WriteChars (char[] buffer, int index, int count);
  240. public abstract void WriteComment (string text);
  241. public abstract void WriteDocType (string name, string pubid, string sysid, string subset);
  242. public void WriteElementString (string localName, string value)
  243. {
  244. WriteStartElement(localName);
  245. WriteString(value);
  246. WriteEndElement();
  247. }
  248. public void WriteElementString (string localName, string ns, string value)
  249. {
  250. WriteStartElement(localName, ns);
  251. WriteString(value);
  252. WriteEndElement();
  253. }
  254. #if NET_2_0
  255. public void WriteElementString (string prefix, string localName, string ns, string value)
  256. {
  257. WriteStartElement(prefix, localName, ns);
  258. WriteString(value);
  259. WriteEndElement();
  260. }
  261. #endif
  262. public abstract void WriteEndAttribute ();
  263. public abstract void WriteEndDocument ();
  264. public abstract void WriteEndElement ();
  265. public abstract void WriteEntityRef (string name);
  266. public abstract void WriteFullEndElement ();
  267. #if NET_2_0
  268. public virtual void WriteName (string name)
  269. {
  270. WriteNameInternal (name);
  271. }
  272. public virtual void WriteNmToken (string name)
  273. {
  274. WriteNmTokenInternal (name);
  275. }
  276. public virtual void WriteQualifiedName (string localName, string ns)
  277. {
  278. WriteQualifiedNameInternal (localName, ns);
  279. }
  280. #else
  281. public abstract void WriteName (string name);
  282. public abstract void WriteNmToken (string name);
  283. public abstract void WriteQualifiedName (string localName, string ns);
  284. #endif
  285. internal void WriteNameInternal (string name)
  286. {
  287. #if NET_2_0
  288. switch (Settings.ConformanceLevel) {
  289. case ConformanceLevel.Document:
  290. case ConformanceLevel.Fragment:
  291. XmlConvert.VerifyName (name);
  292. break;
  293. }
  294. #else
  295. XmlConvert.VerifyName (name);
  296. #endif
  297. WriteString (name);
  298. }
  299. internal virtual void WriteNmTokenInternal (string name)
  300. {
  301. #if NET_2_0
  302. switch (Settings.ConformanceLevel) {
  303. case ConformanceLevel.Document:
  304. case ConformanceLevel.Fragment:
  305. XmlConvert.VerifyNMTOKEN (name);
  306. break;
  307. }
  308. #else
  309. XmlConvert.VerifyNMTOKEN (name);
  310. #endif
  311. WriteString (name);
  312. }
  313. internal void WriteQualifiedNameInternal (string localName, string ns)
  314. {
  315. if (localName == null || localName == String.Empty)
  316. throw new ArgumentException ();
  317. if (ns == null)
  318. ns = String.Empty;
  319. #if NET_2_0
  320. switch (Settings.ConformanceLevel) {
  321. case ConformanceLevel.Document:
  322. case ConformanceLevel.Fragment:
  323. XmlConvert.VerifyNCName (localName);
  324. break;
  325. }
  326. #else
  327. XmlConvert.VerifyNCName (localName);
  328. #endif
  329. string prefix = ns.Length > 0 ? LookupPrefix (ns) : String.Empty;
  330. if (prefix == null)
  331. throw new ArgumentException (String.Format ("Namespace '{0}' is not declared.", ns));
  332. if (prefix != String.Empty) {
  333. WriteString (prefix);
  334. WriteString (":");
  335. WriteString (localName);
  336. }
  337. else
  338. WriteString (localName);
  339. }
  340. #if NET_2_0
  341. [MonoTODO ("defattr handling")]
  342. public virtual void WriteNode (XPathNavigator navigator, bool defattr)
  343. {
  344. if (navigator == null)
  345. throw new ArgumentNullException ("navigator");
  346. switch (navigator.NodeType) {
  347. case XPathNodeType.Attribute:
  348. case XPathNodeType.Namespace:
  349. WriteAttributeString (navigator.Prefix, navigator.LocalName, navigator.NamespaceURI, navigator.Value);
  350. break;
  351. default:
  352. WriteNode (navigator.ReadSubtree (), defattr);
  353. break;
  354. }
  355. }
  356. #endif
  357. public virtual void WriteNode (XmlReader reader, bool defattr)
  358. {
  359. if (reader == null)
  360. throw new ArgumentException ();
  361. if (reader.ReadState == ReadState.Initial) {
  362. reader.Read ();
  363. do {
  364. WriteNode (reader, defattr);
  365. } while (!reader.EOF);
  366. return;
  367. }
  368. switch (reader.NodeType) {
  369. case XmlNodeType.Element:
  370. WriteStartElement (reader.Prefix, reader.LocalName, reader.NamespaceURI);
  371. #if false
  372. WriteAttributes (reader, defattr);
  373. reader.MoveToElement ();
  374. #else
  375. // Well, I found that MS.NET took this way, since
  376. // there was a error-prone SgmlReader that fails
  377. // MoveToNextAttribute().
  378. if (reader.HasAttributes) {
  379. for (int i = 0; i < reader.AttributeCount; i++) {
  380. reader.MoveToAttribute (i);
  381. WriteAttribute (reader, defattr);
  382. }
  383. reader.MoveToElement ();
  384. }
  385. #endif
  386. if (reader.IsEmptyElement)
  387. WriteEndElement ();
  388. else {
  389. int depth = reader.Depth;
  390. reader.Read ();
  391. if (reader.NodeType != XmlNodeType.EndElement) {
  392. do {
  393. WriteNode (reader, defattr);
  394. } while (depth < reader.Depth);
  395. }
  396. WriteFullEndElement ();
  397. }
  398. break;
  399. // In case of XmlAttribute, don't proceed reader, and it will never be written.
  400. case XmlNodeType.Attribute:
  401. return;
  402. case XmlNodeType.Text:
  403. WriteString (reader.Value);
  404. break;
  405. case XmlNodeType.CDATA:
  406. WriteCData (reader.Value);
  407. break;
  408. case XmlNodeType.EntityReference:
  409. WriteEntityRef (reader.Name);
  410. break;
  411. case XmlNodeType.XmlDeclaration:
  412. // LAMESPEC: It means that XmlWriter implementation _must not_ check
  413. // whether PI name is "xml" (it is XML error) or not.
  414. case XmlNodeType.ProcessingInstruction:
  415. WriteProcessingInstruction (reader.Name, reader.Value);
  416. break;
  417. case XmlNodeType.Comment:
  418. WriteComment (reader.Value);
  419. break;
  420. case XmlNodeType.DocumentType:
  421. WriteDocType (reader.Name,
  422. reader ["PUBLIC"], reader ["SYSTEM"], reader.Value);
  423. break;
  424. case XmlNodeType.SignificantWhitespace:
  425. goto case XmlNodeType.Whitespace;
  426. case XmlNodeType.Whitespace:
  427. WriteWhitespace (reader.Value);
  428. break;
  429. case XmlNodeType.EndElement:
  430. WriteFullEndElement ();
  431. break;
  432. case XmlNodeType.EndEntity:
  433. break;
  434. case XmlNodeType.None:
  435. break; // Do nothing, nor reporting errors.
  436. default:
  437. throw new XmlException ("Unexpected node " + reader.Name + " of type " + reader.NodeType);
  438. }
  439. reader.Read ();
  440. }
  441. public abstract void WriteProcessingInstruction (string name, string text);
  442. public abstract void WriteRaw (string data);
  443. public abstract void WriteRaw (char[] buffer, int index, int count);
  444. #if NET_2_0
  445. public void WriteStartAttribute (string localName)
  446. {
  447. WriteStartAttribute (null, localName, null);
  448. }
  449. #endif
  450. public void WriteStartAttribute (string localName, string ns)
  451. {
  452. WriteStartAttribute (null, localName, ns);
  453. }
  454. public abstract void WriteStartAttribute (string prefix, string localName, string ns);
  455. public abstract void WriteStartDocument ();
  456. public abstract void WriteStartDocument (bool standalone);
  457. public void WriteStartElement (string localName)
  458. {
  459. WriteStartElement (null, localName, null);
  460. }
  461. public void WriteStartElement (string localName, string ns)
  462. {
  463. WriteStartElement (null, localName, ns);
  464. }
  465. public abstract void WriteStartElement (string prefix, string localName, string ns);
  466. public abstract void WriteString (string text);
  467. public abstract void WriteSurrogateCharEntity (char lowChar, char highChar);
  468. public abstract void WriteWhitespace (string ws);
  469. #if NET_2_0
  470. [MonoTODO]
  471. public virtual void WriteValue (bool value)
  472. {
  473. WriteString (XQueryConvert.BooleanToString (value));
  474. }
  475. [MonoTODO]
  476. public virtual void WriteValue (DateTime value)
  477. {
  478. WriteString (XmlConvert.ToString (value));
  479. }
  480. [MonoTODO]
  481. public virtual void WriteValue (decimal value)
  482. {
  483. WriteString (XQueryConvert.DecimalToString (value));
  484. }
  485. [MonoTODO]
  486. public virtual void WriteValue (double value)
  487. {
  488. WriteString (XQueryConvert.DoubleToString (value));
  489. }
  490. [MonoTODO]
  491. public virtual void WriteValue (int value)
  492. {
  493. WriteString (XQueryConvert.IntToString (value));
  494. }
  495. [MonoTODO]
  496. public virtual void WriteValue (long value)
  497. {
  498. WriteString (XQueryConvert.IntegerToString (value));
  499. }
  500. [MonoTODO]
  501. public virtual void WriteValue (object value)
  502. {
  503. if (value is string)
  504. WriteString ((string) value);
  505. else if (value is bool)
  506. WriteValue ((bool) value);
  507. else if (value is DateTime)
  508. WriteValue ((DateTime) value);
  509. else if (value is decimal)
  510. WriteValue ((decimal) value);
  511. else if (value is double)
  512. WriteValue ((double) value);
  513. else if (value is int)
  514. WriteValue ((int) value);
  515. else if (value is long)
  516. WriteValue ((long) value);
  517. else if (value is XmlQualifiedName) {
  518. XmlQualifiedName qname = (XmlQualifiedName) value;
  519. WriteQualifiedName (qname.Name, qname.Namespace);
  520. }
  521. else
  522. throw new NotImplementedException ("Argument value is " + value);
  523. }
  524. [MonoTODO]
  525. public virtual void WriteValue (float value)
  526. {
  527. WriteString (XQueryConvert.FloatToString (value));
  528. }
  529. [MonoTODO]
  530. public virtual void WriteValue (string value)
  531. {
  532. WriteString (value);
  533. }
  534. #endif
  535. #endregion
  536. }
  537. }