XmlWriter.cs 17 KB

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