XmlWriter.cs 16 KB

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