XmlTextWriter.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. //
  2. // System.Xml.XmlTextWriter
  3. //
  4. // Author:
  5. // Kral Ferch <[email protected]>
  6. //
  7. // (C) 2002 Kral Ferch
  8. //
  9. using System;
  10. using System.Collections;
  11. using System.IO;
  12. using System.Text;
  13. namespace System.Xml
  14. {
  15. public class XmlTextWriter : XmlWriter
  16. {
  17. #region Fields
  18. TextWriter w;
  19. bool nullEncoding = false;
  20. bool openWriter = true;
  21. bool openStartElement = false;
  22. bool openStartAttribute = false;
  23. bool documentStarted = false;
  24. bool namespaces = true;
  25. bool openAttribute = false;
  26. bool attributeWrittenForElement = false;
  27. Stack openElements = new Stack ();
  28. Formatting formatting = Formatting.None;
  29. int indentation = 2;
  30. char indentChar = ' ';
  31. string indentChars = " ";
  32. char quoteChar = '\"';
  33. int indentLevel = 0;
  34. string indentFormatting;
  35. Stream baseStream = null;
  36. string xmlLang = null;
  37. XmlSpace xmlSpace = XmlSpace.None;
  38. bool openXmlLang = false;
  39. bool openXmlSpace = false;
  40. #endregion
  41. #region Constructors
  42. public XmlTextWriter (TextWriter w) : base ()
  43. {
  44. this.w = w;
  45. nullEncoding = (w.Encoding == null);
  46. try {
  47. baseStream = ((StreamWriter)w).BaseStream;
  48. }
  49. catch (Exception) { }
  50. }
  51. public XmlTextWriter (Stream w, Encoding encoding) : base ()
  52. {
  53. if (encoding == null) {
  54. nullEncoding = true;
  55. encoding = new UTF8Encoding ();
  56. }
  57. this.w = new StreamWriter(w, encoding);
  58. baseStream = w;
  59. }
  60. public XmlTextWriter (string filename, Encoding encoding) :
  61. this (new FileStream (filename, FileMode.Create, FileAccess.Write, FileShare.None), encoding)
  62. {
  63. }
  64. #endregion
  65. #region Properties
  66. public Stream BaseStream {
  67. get { return baseStream; }
  68. }
  69. public Formatting Formatting {
  70. get { return formatting; }
  71. set { formatting = value; }
  72. }
  73. private bool IndentingOverriden
  74. {
  75. get {
  76. if (openElements.Count == 0)
  77. return false;
  78. else
  79. return (((XmlTextWriterOpenElement)openElements.Peek()).IndentingOverriden);
  80. }
  81. set {
  82. if (openElements.Count > 0)
  83. ((XmlTextWriterOpenElement)openElements.Peek()).IndentingOverriden = value;
  84. }
  85. }
  86. public int Indentation {
  87. get { return indentation; }
  88. set {
  89. indentation = value;
  90. UpdateIndentChars ();
  91. }
  92. }
  93. public char IndentChar {
  94. get { return indentChar; }
  95. set {
  96. indentChar = value;
  97. UpdateIndentChars ();
  98. }
  99. }
  100. public bool Namespaces {
  101. get { return namespaces; }
  102. set {
  103. if (ws != WriteState.Start)
  104. throw new InvalidOperationException ("NotInWriteState.");
  105. namespaces = value;
  106. }
  107. }
  108. public char QuoteChar {
  109. get { return quoteChar; }
  110. set {
  111. if ((value != '\'') && (value != '\"'))
  112. throw new ArgumentException ("This is an invalid XML attribute quote character. Valid attribute quote characters are ' and \".");
  113. quoteChar = value;
  114. }
  115. }
  116. public override WriteState WriteState {
  117. get { return ws; }
  118. }
  119. public override string XmlLang {
  120. get {
  121. string xmlLang = null;
  122. int i;
  123. for (i = 0; i < openElements.Count; i++)
  124. {
  125. xmlLang = ((XmlTextWriterOpenElement)openElements.ToArray().GetValue(i)).XmlLang;
  126. if (xmlLang != null)
  127. break;
  128. }
  129. return xmlLang;
  130. }
  131. }
  132. public override XmlSpace XmlSpace {
  133. get {
  134. XmlSpace xmlSpace = XmlSpace.None;
  135. int i;
  136. for (i = 0; i < openElements.Count; i++)
  137. {
  138. xmlSpace = ((XmlTextWriterOpenElement)openElements.ToArray().GetValue(i)).XmlSpace;
  139. if (xmlSpace != XmlSpace.None)
  140. break;
  141. }
  142. return xmlSpace;
  143. }
  144. }
  145. #endregion
  146. #region Methods
  147. private void CheckState ()
  148. {
  149. if (!openWriter) {
  150. throw new InvalidOperationException ("The Writer is closed.");
  151. }
  152. if ((documentStarted == true) && (formatting == Formatting.Indented) && (!IndentingOverriden)) {
  153. indentFormatting = "\r\n";
  154. if (indentLevel > 0) {
  155. for (int i = 0; i < indentLevel; i++)
  156. indentFormatting += indentChars;
  157. }
  158. }
  159. else
  160. indentFormatting = "";
  161. documentStarted = true;
  162. }
  163. public override void Close ()
  164. {
  165. CloseOpenAttributeAndElements ();
  166. w.Close();
  167. ws = WriteState.Closed;
  168. openWriter = false;
  169. }
  170. private void CloseOpenAttributeAndElements ()
  171. {
  172. if (openAttribute)
  173. WriteEndAttribute ();
  174. while (openElements.Count > 0) {
  175. WriteEndElement();
  176. }
  177. }
  178. private void CloseStartElement ()
  179. {
  180. if (openStartElement) {
  181. w.Write(">");
  182. ws = WriteState.Content;
  183. openStartElement = false;
  184. attributeWrittenForElement = false;
  185. }
  186. }
  187. public override void Flush ()
  188. {
  189. w.Flush ();
  190. }
  191. public override string LookupPrefix (string ns)
  192. {
  193. string prefix = namespaceManager.LookupPrefix (ns);
  194. if (prefix == String.Empty)
  195. prefix = null;
  196. return prefix;
  197. }
  198. private void UpdateIndentChars ()
  199. {
  200. indentChars = "";
  201. for (int i = 0; i < indentation; i++)
  202. indentChars += indentChar;
  203. }
  204. public override void WriteBase64 (byte[] buffer, int index, int count)
  205. {
  206. w.Write (Convert.ToBase64String (buffer, index, count));
  207. }
  208. [MonoTODO]
  209. public override void WriteBinHex (byte[] buffer, int index, int count)
  210. {
  211. throw new NotImplementedException ();
  212. }
  213. public override void WriteCData (string text)
  214. {
  215. if (text.IndexOf("]]>") > 0)
  216. throw new ArgumentException ();
  217. CheckState ();
  218. CloseStartElement ();
  219. w.Write("<![CDATA[{0}]]>", text);
  220. }
  221. public override void WriteCharEntity (char ch)
  222. {
  223. Int16 intCh = (Int16)ch;
  224. // Make sure the character is not in the surrogate pair
  225. // character range, 0xd800- 0xdfff
  226. if ((intCh >= -10240) && (intCh <= -8193))
  227. throw new ArgumentException ("Surrogate Pair is invalid.");
  228. w.Write("&#x{0:X};", intCh);
  229. }
  230. [MonoTODO]
  231. public override void WriteChars (char[] buffer, int index, int count)
  232. {
  233. throw new NotImplementedException ();
  234. }
  235. public override void WriteComment (string text)
  236. {
  237. if ((text.EndsWith("-")) || (text.IndexOf("-->") > 0)) {
  238. throw new ArgumentException ();
  239. }
  240. CheckState ();
  241. CloseStartElement ();
  242. w.Write ("<!--{0}-->", text);
  243. }
  244. [MonoTODO]
  245. public override void WriteDocType (string name, string pubid, string sysid, string subset)
  246. {
  247. throw new NotImplementedException ();
  248. }
  249. public override void WriteEndAttribute ()
  250. {
  251. if (!openAttribute)
  252. throw new InvalidOperationException("Token EndAttribute in state Start would result in an invalid XML document.");
  253. CheckState ();
  254. if (openXmlLang) {
  255. w.Write (xmlLang);
  256. openXmlLang = false;
  257. ((XmlTextWriterOpenElement)openElements.Peek()).XmlLang = xmlLang;
  258. }
  259. if (openXmlSpace)
  260. {
  261. w.Write (xmlSpace.ToString ().ToLower ());
  262. openXmlSpace = false;
  263. ((XmlTextWriterOpenElement)openElements.Peek()).XmlSpace = xmlSpace;
  264. }
  265. w.Write ("{0}", quoteChar);
  266. openAttribute = false;
  267. }
  268. public override void WriteEndDocument ()
  269. {
  270. if ((ws == WriteState.Start) || (ws == WriteState.Prolog))
  271. throw new ArgumentException ("This document does not have a root element.");
  272. CloseOpenAttributeAndElements ();
  273. ws = WriteState.Start;
  274. }
  275. public override void WriteEndElement ()
  276. {
  277. WriteEndElementInternal (false);
  278. }
  279. private void WriteEndElementInternal (bool fullEndElement)
  280. {
  281. if (openElements.Count == 0)
  282. throw new InvalidOperationException("There was no XML start tag open.");
  283. indentLevel--;
  284. CheckState ();
  285. if (openStartElement) {
  286. if (openAttribute)
  287. WriteEndAttribute ();
  288. if (fullEndElement)
  289. w.Write ("></{0}>", ((XmlTextWriterOpenElement)openElements.Peek ()).Name);
  290. else
  291. w.Write (" />");
  292. openElements.Pop ();
  293. openStartElement = false;
  294. } else {
  295. w.Write ("{0}</{1}>", indentFormatting, openElements.Pop ());
  296. }
  297. namespaceManager.PopScope();
  298. }
  299. [MonoTODO]
  300. public override void WriteEntityRef (string name)
  301. {
  302. throw new NotImplementedException ();
  303. }
  304. public override void WriteFullEndElement ()
  305. {
  306. WriteEndElementInternal (true);
  307. }
  308. [MonoTODO]
  309. public override void WriteName (string name)
  310. {
  311. throw new NotImplementedException ();
  312. }
  313. [MonoTODO]
  314. public override void WriteNmToken (string name)
  315. {
  316. throw new NotImplementedException ();
  317. }
  318. public override void WriteProcessingInstruction (string name, string text)
  319. {
  320. if ((name == null) || (name == string.Empty) || (name.IndexOf("?>") > 0) || (text.IndexOf("?>") > 0)) {
  321. throw new ArgumentException ();
  322. }
  323. CheckState ();
  324. CloseStartElement ();
  325. w.Write ("{0}<?{1} {2}?>", indentFormatting, name, text);
  326. }
  327. [MonoTODO]
  328. public override void WriteQualifiedName (string localName, string ns)
  329. {
  330. if (localName == null || localName == String.Empty)
  331. throw new ArgumentException ();
  332. CheckState ();
  333. w.Write ("{0}:{1}", ns, localName);
  334. }
  335. public override void WriteRaw (string data)
  336. {
  337. WriteStringInternal (data, false);
  338. }
  339. [MonoTODO]
  340. public override void WriteRaw (char[] buffer, int index, int count)
  341. {
  342. throw new NotImplementedException ();
  343. }
  344. public override void WriteStartAttribute (string prefix, string localName, string ns)
  345. {
  346. if ((prefix == "xml") && (localName == "lang"))
  347. openXmlLang = true;
  348. if ((prefix == "xml") && (localName == "space"))
  349. openXmlSpace = true;
  350. if ((prefix == "xmlns") && (localName == "xmlns"))
  351. throw new ArgumentException ("Prefixes beginning with \"xml\" (regardless of whether the characters are uppercase, lowercase, or some combination thereof) are reserved for use by XML.");
  352. CheckState ();
  353. if (ws == WriteState.Content)
  354. throw new InvalidOperationException ("Token StartAttribute in state " + WriteState + " would result in an invalid XML document.");
  355. if (prefix == null)
  356. prefix = String.Empty;
  357. if (ns == null)
  358. ns = String.Empty;
  359. string formatPrefix = "";
  360. string formatSpace = "";
  361. if (ns != String.Empty)
  362. {
  363. string existingPrefix = namespaceManager.LookupPrefix (ns);
  364. if (prefix == String.Empty)
  365. prefix = existingPrefix;
  366. }
  367. if (prefix != String.Empty)
  368. {
  369. formatPrefix = prefix + ":";
  370. }
  371. if (openStartElement || attributeWrittenForElement)
  372. formatSpace = " ";
  373. w.Write ("{0}{1}{2}={3}", formatSpace, formatPrefix, localName, quoteChar);
  374. openAttribute = true;
  375. attributeWrittenForElement = true;
  376. ws = WriteState.Attribute;
  377. }
  378. public override void WriteStartDocument ()
  379. {
  380. WriteStartDocument ("");
  381. }
  382. public override void WriteStartDocument (bool standalone)
  383. {
  384. string standaloneFormatting;
  385. if (standalone == true)
  386. standaloneFormatting = String.Format (" standalone={0}yes{0}", quoteChar);
  387. else
  388. standaloneFormatting = String.Format (" standalone={0}no{0}", quoteChar);
  389. WriteStartDocument (standaloneFormatting);
  390. }
  391. private void WriteStartDocument (string standaloneFormatting)
  392. {
  393. if (documentStarted == true)
  394. throw new InvalidOperationException("WriteStartDocument should be the first call.");
  395. CheckState ();
  396. string encodingFormatting = "";
  397. if (!nullEncoding)
  398. encodingFormatting = String.Format (" encoding={0}{1}{0}", quoteChar, w.Encoding.HeaderName);
  399. w.Write("<?xml version={0}1.0{0}{1}{2}?>", quoteChar, encodingFormatting, standaloneFormatting);
  400. ws = WriteState.Prolog;
  401. }
  402. public override void WriteStartElement (string prefix, string localName, string ns)
  403. {
  404. if (!Namespaces && (((prefix != null) && (prefix != String.Empty))
  405. || ((ns != null) && (ns != String.Empty))))
  406. throw new ArgumentException ("Cannot set the namespace if Namespaces is 'false'.");
  407. WriteStartElementInternal (prefix, localName, ns);
  408. }
  409. private void WriteStartElementInternal (string prefix, string localName, string ns)
  410. {
  411. if (prefix == null)
  412. prefix = String.Empty;
  413. if ((prefix != String.Empty) && ((ns == null) || (ns == String.Empty)))
  414. throw new ArgumentException ("Cannot use a prefix with an empty namespace.");
  415. CheckState ();
  416. CloseStartElement ();
  417. string formatXmlns = "";
  418. string formatPrefix = "";
  419. if(ns != null)
  420. {
  421. if (ns != String.Empty)
  422. {
  423. string existingPrefix = namespaceManager.LookupPrefix (ns);
  424. if (prefix == String.Empty)
  425. prefix = existingPrefix;
  426. if (prefix != existingPrefix)
  427. formatXmlns = String.Format (" xmlns:{0}={1}{2}{1}", prefix, quoteChar, ns);
  428. else if (existingPrefix == String.Empty)
  429. formatXmlns = String.Format (" xmlns={0}{1}{0}", quoteChar, ns);
  430. }
  431. else if ((prefix == String.Empty) && (namespaceManager.LookupNamespace(prefix) != String.Empty)) {
  432. formatXmlns = String.Format (" xmlns={0}{0}", quoteChar);
  433. }
  434. if (prefix != String.Empty) {
  435. formatPrefix = prefix + ":";
  436. }
  437. }
  438. w.Write ("{0}<{1}{2}{3}", indentFormatting, formatPrefix, localName, formatXmlns);
  439. openElements.Push (new XmlTextWriterOpenElement (formatPrefix + localName));
  440. ws = WriteState.Element;
  441. openStartElement = true;
  442. namespaceManager.PushScope ();
  443. if(ns != null)
  444. {
  445. namespaceManager.AddNamespace (prefix, ns);
  446. }
  447. indentLevel++;
  448. }
  449. public override void WriteString (string text)
  450. {
  451. if (ws == WriteState.Prolog)
  452. throw new InvalidOperationException ("Token content in state Prolog would result in an invalid XML document.");
  453. WriteStringInternal (text, true);
  454. }
  455. private void WriteStringInternal (string text, bool entitize)
  456. {
  457. if (text == null)
  458. text = String.Empty;
  459. if (text != String.Empty)
  460. {
  461. CheckState ();
  462. if (entitize)
  463. {
  464. text = text.Replace ("&", "&amp;");
  465. text = text.Replace ("<", "&lt;");
  466. text = text.Replace (">", "&gt;");
  467. if (openAttribute)
  468. {
  469. if (quoteChar == '"')
  470. text = text.Replace ("\"", "&quot;");
  471. else
  472. text = text.Replace ("'", "&apos;");
  473. }
  474. }
  475. if (!openAttribute)
  476. {
  477. IndentingOverriden = true;
  478. CloseStartElement ();
  479. }
  480. if (!openXmlLang && !openXmlSpace)
  481. w.Write (text);
  482. else
  483. {
  484. if (openXmlLang)
  485. xmlLang = text;
  486. else
  487. {
  488. switch (text)
  489. {
  490. case "default":
  491. xmlSpace = XmlSpace.Default;
  492. break;
  493. case "preserve":
  494. xmlSpace = XmlSpace.Preserve;
  495. break;
  496. default:
  497. throw new ArgumentException ("'{0}' is an invalid xml:space value.");
  498. }
  499. }
  500. }
  501. }
  502. }
  503. [MonoTODO]
  504. public override void WriteSurrogateCharEntity (char lowChar, char highChar)
  505. {
  506. throw new NotImplementedException ();
  507. }
  508. public override void WriteWhitespace (string ws)
  509. {
  510. foreach (char c in ws) {
  511. if ((c != ' ') && (c != '\t') && (c != '\r') && (c != '\n'))
  512. throw new ArgumentException ();
  513. }
  514. w.Write (ws);
  515. }
  516. #endregion
  517. }
  518. }