XmlWriter.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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 (ns == null)
  306. ns = String.Empty;
  307. #if NET_2_0
  308. switch (Settings.ConformanceLevel) {
  309. case ConformanceLevel.Document:
  310. case ConformanceLevel.Fragment:
  311. XmlConvert.VerifyNCName (localName);
  312. break;
  313. }
  314. #else
  315. XmlConvert.VerifyNCName (localName);
  316. #endif
  317. string prefix = ns.Length > 0 ? LookupPrefix (ns) : String.Empty;
  318. if (prefix != String.Empty) {
  319. WriteString (prefix);
  320. WriteString (":");
  321. WriteString (localName);
  322. }
  323. else
  324. WriteString (localName);
  325. }
  326. #if NET_2_0
  327. [MonoTODO ("defattr handling")]
  328. public virtual void WriteNode (XPathNavigator navigator, bool defattr)
  329. {
  330. if (navigator == null)
  331. throw new ArgumentNullException ("navigator");
  332. switch (navigator.NodeType) {
  333. case XPathNodeType.Attribute:
  334. case XPathNodeType.Namespace:
  335. WriteAttributeString (navigator.Prefix, navigator.LocalName, navigator.NamespaceURI, navigator.Value);
  336. break;
  337. default:
  338. WriteNode (navigator.ReadSubtree (), defattr);
  339. break;
  340. }
  341. }
  342. #endif
  343. public virtual void WriteNode (XmlReader reader, bool defattr)
  344. {
  345. if (reader == null)
  346. throw new ArgumentException ();
  347. if (reader.ReadState == ReadState.Initial) {
  348. reader.Read ();
  349. do {
  350. WriteNode (reader, defattr);
  351. } while (!reader.EOF);
  352. return;
  353. }
  354. switch (reader.NodeType) {
  355. case XmlNodeType.Element:
  356. WriteStartElement (reader.Prefix, reader.LocalName, reader.NamespaceURI);
  357. #if false
  358. WriteAttributes (reader, defattr);
  359. reader.MoveToElement ();
  360. #else
  361. // Well, I found that MS.NET took this way, since
  362. // there was a error-prone SgmlReader that fails
  363. // MoveToNextAttribute().
  364. if (reader.HasAttributes) {
  365. for (int i = 0; i < reader.AttributeCount; i++) {
  366. reader.MoveToAttribute (i);
  367. WriteAttribute (reader, defattr);
  368. }
  369. reader.MoveToElement ();
  370. }
  371. #endif
  372. if (reader.IsEmptyElement)
  373. WriteEndElement ();
  374. else {
  375. int depth = reader.Depth;
  376. reader.Read ();
  377. if (reader.NodeType != XmlNodeType.EndElement) {
  378. do {
  379. WriteNode (reader, defattr);
  380. } while (depth < reader.Depth);
  381. }
  382. WriteFullEndElement ();
  383. }
  384. break;
  385. // In case of XmlAttribute, don't proceed reader, and it will never be written.
  386. case XmlNodeType.Attribute:
  387. return;
  388. case XmlNodeType.Text:
  389. WriteString (reader.Value);
  390. break;
  391. case XmlNodeType.CDATA:
  392. WriteCData (reader.Value);
  393. break;
  394. case XmlNodeType.EntityReference:
  395. WriteEntityRef (reader.Name);
  396. break;
  397. case XmlNodeType.XmlDeclaration:
  398. // LAMESPEC: It means that XmlWriter implementation _must not_ check
  399. // whether PI name is "xml" (it is XML error) or not.
  400. case XmlNodeType.ProcessingInstruction:
  401. WriteProcessingInstruction (reader.Name, reader.Value);
  402. break;
  403. case XmlNodeType.Comment:
  404. WriteComment (reader.Value);
  405. break;
  406. case XmlNodeType.DocumentType:
  407. WriteDocType (reader.Name,
  408. reader ["PUBLIC"], reader ["SYSTEM"], reader.Value);
  409. break;
  410. case XmlNodeType.SignificantWhitespace:
  411. goto case XmlNodeType.Whitespace;
  412. case XmlNodeType.Whitespace:
  413. WriteWhitespace (reader.Value);
  414. break;
  415. case XmlNodeType.EndElement:
  416. WriteFullEndElement ();
  417. break;
  418. case XmlNodeType.EndEntity:
  419. break;
  420. case XmlNodeType.None:
  421. break; // Do nothing, nor reporting errors.
  422. default:
  423. throw new XmlException ("Unexpected node " + reader.Name + " of type " + reader.NodeType);
  424. }
  425. reader.Read ();
  426. }
  427. public abstract void WriteProcessingInstruction (string name, string text);
  428. public abstract void WriteRaw (string data);
  429. public abstract void WriteRaw (char[] buffer, int index, int count);
  430. #if NET_2_0
  431. public void WriteStartAttribute (string localName)
  432. {
  433. WriteStartAttribute (null, localName, null);
  434. }
  435. #endif
  436. public void WriteStartAttribute (string localName, string ns)
  437. {
  438. WriteStartAttribute (null, localName, ns);
  439. }
  440. public abstract void WriteStartAttribute (string prefix, string localName, string ns);
  441. public abstract void WriteStartDocument ();
  442. public abstract void WriteStartDocument (bool standalone);
  443. public void WriteStartElement (string localName)
  444. {
  445. WriteStartElement (null, localName, null);
  446. }
  447. public void WriteStartElement (string localName, string ns)
  448. {
  449. WriteStartElement (null, localName, ns);
  450. }
  451. public abstract void WriteStartElement (string prefix, string localName, string ns);
  452. public abstract void WriteString (string text);
  453. public abstract void WriteSurrogateCharEntity (char lowChar, char highChar);
  454. public abstract void WriteWhitespace (string ws);
  455. #if NET_2_0
  456. [MonoTODO]
  457. public virtual void WriteValue (bool value)
  458. {
  459. WriteString (XQueryConvert.BooleanToString (value));
  460. }
  461. [MonoTODO]
  462. public virtual void WriteValue (DateTime value)
  463. {
  464. WriteString (XmlConvert.ToString (value));
  465. }
  466. [MonoTODO]
  467. public virtual void WriteValue (Decimal value)
  468. {
  469. WriteString (XQueryConvert.DecimalToString (value));
  470. }
  471. [MonoTODO]
  472. public virtual void WriteValue (double value)
  473. {
  474. WriteString (XQueryConvert.DoubleToString (value));
  475. }
  476. [MonoTODO]
  477. public virtual void WriteValue (int value)
  478. {
  479. WriteString (XQueryConvert.IntToString (value));
  480. }
  481. [MonoTODO]
  482. public virtual void WriteValue (long value)
  483. {
  484. WriteString (XQueryConvert.IntegerToString (value));
  485. }
  486. [MonoTODO]
  487. public virtual void WriteValue (Stream value)
  488. {
  489. throw new NotImplementedException ();
  490. }
  491. [MonoTODO]
  492. public virtual void WriteValue (TextReader value)
  493. {
  494. throw new NotImplementedException ();
  495. }
  496. [MonoTODO]
  497. public virtual void WriteValue (object value)
  498. {
  499. if (value is string)
  500. WriteString ((string) value);
  501. else if (value is bool)
  502. WriteValue ((bool) value);
  503. else if (value is DateTime)
  504. WriteValue ((DateTime) value);
  505. else if (value is decimal)
  506. WriteValue ((decimal) value);
  507. else if (value is double)
  508. WriteValue ((double) value);
  509. else if (value is int)
  510. WriteValue ((int) value);
  511. else if (value is long)
  512. WriteValue ((long) value);
  513. else if (value is XmlQualifiedName) {
  514. XmlQualifiedName qname = (XmlQualifiedName) value;
  515. WriteQualifiedName (qname.Name, qname.Namespace);
  516. }
  517. else
  518. throw new NotImplementedException ("Argument value is " + value);
  519. }
  520. [MonoTODO]
  521. public virtual void WriteValue (float value)
  522. {
  523. WriteString (XQueryConvert.FloatToString (value));
  524. }
  525. [MonoTODO]
  526. public virtual void WriteValue (string value)
  527. {
  528. WriteString (value);
  529. }
  530. #endif
  531. #endregion
  532. }
  533. }