XmlWriter.cs 16 KB

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