2
0

XmlWriter.cs 17 KB

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