XmlWriter.cs 17 KB

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