XmlWriter.cs 16 KB

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