XmlWriter.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  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. // (C) 2004-2007 Novell, Inc.
  11. //
  12. //
  13. // Permission is hereby granted, free of charge, to any person obtaining
  14. // a copy of this software and associated documentation files (the
  15. // "Software"), to deal in the Software without restriction, including
  16. // without limitation the rights to use, copy, modify, merge, publish,
  17. // distribute, sublicense, and/or sell copies of the Software, and to
  18. // permit persons to whom the Software is furnished to do so, subject to
  19. // the following conditions:
  20. //
  21. // The above copyright notice and this permission notice shall be
  22. // included in all copies or substantial portions of the Software.
  23. //
  24. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  28. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  29. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. //
  32. using System;
  33. using System.Collections;
  34. using System.IO;
  35. using System.Text;
  36. #if NET_2_0 && !NET_2_1
  37. using System.Xml.XPath;
  38. #endif
  39. namespace System.Xml
  40. {
  41. #if NET_2_0
  42. public abstract class XmlWriter : IDisposable
  43. #else
  44. public abstract class XmlWriter
  45. #endif
  46. {
  47. #if NET_2_0
  48. XmlWriterSettings settings;
  49. #endif
  50. #region Constructors
  51. protected XmlWriter () { }
  52. #endregion
  53. #region Properties
  54. #if NET_2_0
  55. public virtual XmlWriterSettings Settings {
  56. get {
  57. if (settings == null)
  58. settings = new XmlWriterSettings ();
  59. return settings;
  60. }
  61. }
  62. #endif
  63. public abstract WriteState WriteState { get; }
  64. #if NET_2_0
  65. public virtual string XmlLang {
  66. get { return null; }
  67. }
  68. public virtual XmlSpace XmlSpace {
  69. get { return XmlSpace.None; }
  70. }
  71. #else
  72. public abstract string XmlLang { get; }
  73. public abstract XmlSpace XmlSpace { get; }
  74. #endif
  75. #endregion
  76. #region Methods
  77. public abstract void Close ();
  78. #if NET_2_0
  79. public static XmlWriter Create (Stream stream)
  80. {
  81. return Create (stream, null);
  82. }
  83. public static XmlWriter Create (string file)
  84. {
  85. return Create (file, null);
  86. }
  87. public static XmlWriter Create (TextWriter writer)
  88. {
  89. return Create (writer, null);
  90. }
  91. public static XmlWriter Create (XmlWriter writer)
  92. {
  93. return Create (writer, null);
  94. }
  95. public static XmlWriter Create (StringBuilder builder)
  96. {
  97. return Create (builder, null);
  98. }
  99. public static XmlWriter Create (Stream stream, XmlWriterSettings settings)
  100. {
  101. Encoding enc = settings != null ? settings.Encoding : Encoding.UTF8;
  102. return Create (new StreamWriter (stream, enc), settings);
  103. }
  104. public static XmlWriter Create (string file, XmlWriterSettings settings)
  105. {
  106. Encoding enc = settings != null ? settings.Encoding : Encoding.UTF8;
  107. return CreateTextWriter (new StreamWriter (file, false, enc), settings, true);
  108. }
  109. public static XmlWriter Create (StringBuilder builder, XmlWriterSettings settings)
  110. {
  111. return Create (new StringWriter (builder), settings);
  112. }
  113. public static XmlWriter Create (TextWriter writer, XmlWriterSettings settings)
  114. {
  115. if (settings == null)
  116. settings = new XmlWriterSettings ();
  117. return CreateTextWriter (writer, settings, settings.CloseOutput);
  118. }
  119. public static XmlWriter Create (XmlWriter writer, XmlWriterSettings settings)
  120. {
  121. if (settings == null)
  122. settings = new XmlWriterSettings ();
  123. writer.settings = settings;
  124. return writer;
  125. }
  126. private static XmlWriter CreateTextWriter (TextWriter writer, XmlWriterSettings settings, bool closeOutput)
  127. {
  128. if (settings == null)
  129. settings = new XmlWriterSettings ();
  130. XmlTextWriter xtw = new XmlTextWriter (writer, settings, closeOutput);
  131. return Create (xtw, settings);
  132. }
  133. protected virtual void Dispose (bool disposing)
  134. {
  135. Close ();
  136. }
  137. void IDisposable.Dispose ()
  138. {
  139. Dispose (false);
  140. }
  141. #endif
  142. public abstract void Flush ();
  143. public abstract string LookupPrefix (string ns);
  144. private void WriteAttribute (XmlReader reader, bool defattr)
  145. {
  146. if (!defattr && reader.IsDefault)
  147. return;
  148. WriteStartAttribute (reader.Prefix, reader.LocalName, reader.NamespaceURI);
  149. #if NET_2_1
  150. // no ReadAttributeValue() in 2.1 profile.
  151. WriteString (reader.Value);
  152. #else
  153. while (reader.ReadAttributeValue ()) {
  154. switch (reader.NodeType) {
  155. case XmlNodeType.Text:
  156. WriteString (reader.Value);
  157. break;
  158. case XmlNodeType.EntityReference:
  159. WriteEntityRef (reader.Name);
  160. break;
  161. }
  162. }
  163. #endif
  164. WriteEndAttribute ();
  165. }
  166. public virtual void WriteAttributes (XmlReader reader, bool defattr)
  167. {
  168. if(reader == null)
  169. throw new ArgumentException("null XmlReader specified.", "reader");
  170. switch (reader.NodeType) {
  171. case XmlNodeType.XmlDeclaration:
  172. WriteAttributeString ("version", reader ["version"]);
  173. if (reader ["encoding"] != null)
  174. WriteAttributeString ("encoding", reader ["encoding"]);
  175. if (reader ["standalone"] != null)
  176. WriteAttributeString ("standalone", reader ["standalone"]);
  177. break;
  178. case XmlNodeType.Element:
  179. if (reader.MoveToFirstAttribute ())
  180. goto case XmlNodeType.Attribute;
  181. break;
  182. case XmlNodeType.Attribute:
  183. do {
  184. WriteAttribute (reader, defattr);
  185. } while (reader.MoveToNextAttribute ());
  186. reader.MoveToElement ();
  187. break;
  188. default:
  189. throw new XmlException("NodeType is not one of Element, Attribute, nor XmlDeclaration.");
  190. }
  191. }
  192. public void WriteAttributeString (string localName, string value)
  193. {
  194. WriteAttributeString ("", localName, null, value);
  195. }
  196. public void WriteAttributeString (string localName, string ns, string value)
  197. {
  198. WriteAttributeString ("", localName, ns, value);
  199. }
  200. public void WriteAttributeString (string prefix, string localName, string ns, string value)
  201. {
  202. // In MS.NET (1.0), this check is done *here*, not at WriteStartAttribute.
  203. // (XmlTextWriter.WriteStartAttribute("xmlns", "anyname", null) throws an exception.
  204. WriteStartAttribute (prefix, localName, ns);
  205. if (value != null && value.Length > 0)
  206. WriteString (value);
  207. WriteEndAttribute ();
  208. }
  209. public abstract void WriteBase64 (byte[] buffer, int index, int count);
  210. #if NET_2_0
  211. public virtual void WriteBinHex (byte [] buffer, int index, int count)
  212. {
  213. StringWriter sw = new StringWriter ();
  214. XmlConvert.WriteBinHex (buffer, index, count, sw);
  215. WriteString (sw.ToString ());
  216. }
  217. #else
  218. public abstract void WriteBinHex (byte[] buffer, int index, int count);
  219. #endif
  220. public abstract void WriteCData (string text);
  221. public abstract void WriteCharEntity (char ch);
  222. public abstract void WriteChars (char[] buffer, int index, int count);
  223. public abstract void WriteComment (string text);
  224. public abstract void WriteDocType (string name, string pubid, string sysid, string subset);
  225. public void WriteElementString (string localName, string value)
  226. {
  227. WriteStartElement(localName);
  228. if (value != null && value.Length > 0)
  229. WriteString(value);
  230. WriteEndElement();
  231. }
  232. public void WriteElementString (string localName, string ns, string value)
  233. {
  234. WriteStartElement(localName, ns);
  235. if (value != null && value.Length > 0)
  236. WriteString(value);
  237. WriteEndElement();
  238. }
  239. #if NET_2_0
  240. public void WriteElementString (string prefix, string localName, string ns, string value)
  241. {
  242. WriteStartElement(prefix, localName, ns);
  243. if (value != null && value.Length > 0)
  244. WriteString(value);
  245. WriteEndElement();
  246. }
  247. #endif
  248. public abstract void WriteEndAttribute ();
  249. public abstract void WriteEndDocument ();
  250. public abstract void WriteEndElement ();
  251. public abstract void WriteEntityRef (string name);
  252. public abstract void WriteFullEndElement ();
  253. #if NET_2_0
  254. public virtual void WriteName (string name)
  255. {
  256. WriteNameInternal (name);
  257. }
  258. public virtual void WriteNmToken (string name)
  259. {
  260. WriteNmTokenInternal (name);
  261. }
  262. public virtual void WriteQualifiedName (string localName, string ns)
  263. {
  264. WriteQualifiedNameInternal (localName, ns);
  265. }
  266. #else
  267. public abstract void WriteName (string name);
  268. public abstract void WriteNmToken (string name);
  269. public abstract void WriteQualifiedName (string localName, string ns);
  270. #endif
  271. internal void WriteNameInternal (string name)
  272. {
  273. #if NET_2_0
  274. switch (Settings.ConformanceLevel) {
  275. case ConformanceLevel.Document:
  276. case ConformanceLevel.Fragment:
  277. XmlConvert.VerifyName (name);
  278. break;
  279. }
  280. #else
  281. XmlConvert.VerifyName (name);
  282. #endif
  283. WriteString (name);
  284. }
  285. internal virtual void WriteNmTokenInternal (string name)
  286. {
  287. bool valid = true;
  288. #if NET_2_0
  289. switch (Settings.ConformanceLevel) {
  290. case ConformanceLevel.Document:
  291. case ConformanceLevel.Fragment:
  292. valid = XmlChar.IsNmToken (name);
  293. break;
  294. }
  295. #else
  296. valid = XmlChar.IsNmToken (name);
  297. #endif
  298. if (!valid)
  299. throw new ArgumentException ("Argument name is not a valid NMTOKEN.");
  300. WriteString (name);
  301. }
  302. internal void WriteQualifiedNameInternal (string localName, string ns)
  303. {
  304. if (localName == null || localName == String.Empty)
  305. throw new ArgumentException ();
  306. if (ns == null)
  307. ns = String.Empty;
  308. #if NET_2_0
  309. switch (Settings.ConformanceLevel) {
  310. case ConformanceLevel.Document:
  311. case ConformanceLevel.Fragment:
  312. XmlConvert.VerifyNCName (localName);
  313. break;
  314. }
  315. #else
  316. XmlConvert.VerifyNCName (localName);
  317. #endif
  318. string prefix = ns.Length > 0 ? LookupPrefix (ns) : String.Empty;
  319. if (prefix == null)
  320. throw new ArgumentException (String.Format ("Namespace '{0}' is not declared.", ns));
  321. if (prefix != String.Empty) {
  322. WriteString (prefix);
  323. WriteString (":");
  324. WriteString (localName);
  325. }
  326. else
  327. WriteString (localName);
  328. }
  329. #if NET_2_0 && !NET_2_1
  330. [MonoTODO] // FIXME: test defattr handling
  331. public virtual void WriteNode (XPathNavigator navigator, bool defattr)
  332. {
  333. if (navigator == null)
  334. throw new ArgumentNullException ("navigator");
  335. switch (navigator.NodeType) {
  336. case XPathNodeType.Attribute:
  337. if (defattr || navigator.SchemaInfo == null ||
  338. !navigator.SchemaInfo.IsDefault)
  339. WriteAttributeString (navigator.Prefix,
  340. navigator.LocalName,
  341. navigator.NamespaceURI,
  342. navigator.Value);
  343. break;
  344. case XPathNodeType.Namespace:
  345. if (defattr || navigator.SchemaInfo == null ||
  346. !navigator.SchemaInfo.IsDefault)
  347. WriteAttributeString (navigator.Prefix,
  348. navigator.LocalName == String.Empty ? "xmlns" : navigator.LocalName,
  349. "http://www.w3.org/2000/xmlns/",
  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. public virtual void WriteValue (bool value)
  519. {
  520. WriteString (XQueryConvert.BooleanToString (value));
  521. }
  522. public virtual void WriteValue (DateTime value)
  523. {
  524. WriteString (XmlConvert.ToString (value));
  525. }
  526. public virtual void WriteValue (decimal value)
  527. {
  528. WriteString (XQueryConvert.DecimalToString (value));
  529. }
  530. public virtual void WriteValue (double value)
  531. {
  532. WriteString (XQueryConvert.DoubleToString (value));
  533. }
  534. public virtual void WriteValue (int value)
  535. {
  536. WriteString (XQueryConvert.IntToString (value));
  537. }
  538. public virtual void WriteValue (long value)
  539. {
  540. WriteString (XQueryConvert.IntegerToString (value));
  541. }
  542. public virtual void WriteValue (object value)
  543. {
  544. if (value == null)
  545. throw new ArgumentNullException ("value");
  546. if (value is string)
  547. WriteString ((string) value);
  548. else if (value is bool)
  549. WriteValue ((bool) value);
  550. else if (value is byte)
  551. WriteValue ((int) value);
  552. else if (value is byte [])
  553. WriteBase64 ((byte []) value, 0, ((byte []) value).Length);
  554. else if (value is char [])
  555. WriteChars ((char []) value, 0, ((char []) value).Length);
  556. else if (value is DateTime)
  557. WriteValue ((DateTime) value);
  558. else if (value is decimal)
  559. WriteValue ((decimal) value);
  560. else if (value is double)
  561. WriteValue ((double) value);
  562. else if (value is short)
  563. WriteValue ((int) value);
  564. else if (value is int)
  565. WriteValue ((int) value);
  566. else if (value is long)
  567. WriteValue ((long) value);
  568. else if (value is float)
  569. WriteValue ((float) value);
  570. else if (value is TimeSpan) // undocumented
  571. WriteString (XmlConvert.ToString ((TimeSpan) value));
  572. else if (value is XmlQualifiedName) {
  573. XmlQualifiedName qname = (XmlQualifiedName) value;
  574. if (!qname.Equals (XmlQualifiedName.Empty)) {
  575. if (qname.Namespace.Length > 0 && LookupPrefix (qname.Namespace) == null)
  576. throw new InvalidCastException (String.Format ("The QName '{0}' cannot be written. No corresponding prefix is declared", qname));
  577. WriteQualifiedName (qname.Name, qname.Namespace);
  578. }
  579. else
  580. WriteString (String.Empty);
  581. }
  582. else if (value is IEnumerable) {
  583. bool follow = false;
  584. foreach (object obj in (IEnumerable) value) {
  585. if (follow)
  586. WriteString (" ");
  587. else
  588. follow = true;
  589. WriteValue (obj);
  590. }
  591. }
  592. else
  593. throw new InvalidCastException (String.Format ("Type '{0}' cannot be cast to string", value.GetType ()));
  594. }
  595. public virtual void WriteValue (float value)
  596. {
  597. WriteString (XQueryConvert.FloatToString (value));
  598. }
  599. public virtual void WriteValue (string value)
  600. {
  601. WriteString (value);
  602. }
  603. #endif
  604. #endregion
  605. }
  606. }