XmlWriter.cs 16 KB

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