2
0

XmlTextWriter.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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. protected TextWriter w;
  19. protected bool nullEncoding = false;
  20. protected bool openWriter = true;
  21. protected bool openStartElement = false;
  22. protected bool openStartAttribute = false;
  23. protected bool documentStarted = false;
  24. protected bool namespaces = true;
  25. protected bool openAttribute = false;
  26. protected Stack openElements = new Stack ();
  27. protected Formatting formatting = Formatting.None;
  28. protected int indentation = 2;
  29. protected char indentChar = ' ';
  30. protected string indentChars = " ";
  31. protected char quoteChar = '\"';
  32. protected int indentLevel = 0;
  33. protected string indentFormatting;
  34. protected Stream baseStream = null;
  35. protected string xmlLang = null;
  36. protected XmlSpace xmlSpace = XmlSpace.None;
  37. protected bool openXmlLang = false;
  38. protected bool openXmlSpace = false;
  39. #endregion
  40. #region Constructors
  41. public XmlTextWriter (TextWriter w) : base ()
  42. {
  43. this.w = w;
  44. try {
  45. baseStream = ((StreamWriter)w).BaseStream;
  46. }
  47. catch (Exception) { }
  48. }
  49. public XmlTextWriter (Stream w, Encoding encoding) : base ()
  50. {
  51. if (encoding == null) {
  52. nullEncoding = true;
  53. encoding = new UTF8Encoding ();
  54. }
  55. this.w = new StreamWriter(w, encoding);
  56. baseStream = w;
  57. }
  58. public XmlTextWriter (string filename, Encoding encoding) : base ()
  59. {
  60. this.w = new StreamWriter(filename, false, encoding);
  61. baseStream = ((StreamWriter)w).BaseStream;
  62. }
  63. #endregion
  64. #region Properties
  65. public Stream BaseStream {
  66. get { return baseStream; }
  67. }
  68. public Formatting Formatting {
  69. get { return formatting; }
  70. set { formatting = value; }
  71. }
  72. public bool IndentingOverriden
  73. {
  74. get {
  75. if (openElements.Count == 0)
  76. return false;
  77. else
  78. return (((XmlTextWriterOpenElement)openElements.Peek()).IndentingOverriden);
  79. }
  80. set {
  81. if (openElements.Count > 0)
  82. ((XmlTextWriterOpenElement)openElements.Peek()).IndentingOverriden = value;
  83. }
  84. }
  85. public int Indentation {
  86. get { return indentation; }
  87. set {
  88. indentation = value;
  89. UpdateIndentChars ();
  90. }
  91. }
  92. public char IndentChar {
  93. get { return indentChar; }
  94. set {
  95. indentChar = value;
  96. UpdateIndentChars ();
  97. }
  98. }
  99. public bool Namespaces {
  100. get { return namespaces; }
  101. set {
  102. if (ws != WriteState.Start)
  103. throw new InvalidOperationException ("NotInWriteState.");
  104. namespaces = value;
  105. }
  106. }
  107. [MonoTODO]
  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. while (openElements.Count > 0) {
  166. WriteEndElement();
  167. }
  168. w.Close();
  169. ws = WriteState.Closed;
  170. openWriter = false;
  171. }
  172. private void CloseStartElement ()
  173. {
  174. if (openStartElement)
  175. {
  176. w.Write(">");
  177. ws = WriteState.Content;
  178. openStartElement = false;
  179. }
  180. }
  181. public override void Flush ()
  182. {
  183. w.Flush ();
  184. }
  185. [MonoTODO]
  186. public override string LookupPrefix (string ns)
  187. {
  188. throw new NotImplementedException ();
  189. }
  190. private void UpdateIndentChars ()
  191. {
  192. indentChars = "";
  193. for (int i = 0; i < indentation; i++)
  194. indentChars += indentChar;
  195. }
  196. [MonoTODO]
  197. public override void WriteBase64 (byte[] buffer, int index, int count)
  198. {
  199. throw new NotImplementedException ();
  200. }
  201. [MonoTODO]
  202. public override void WriteBinHex (byte[] buffer, int index, int count)
  203. {
  204. throw new NotImplementedException ();
  205. }
  206. public override void WriteCData (string text)
  207. {
  208. if (text.IndexOf("]]>") > 0)
  209. {
  210. throw new ArgumentException ();
  211. }
  212. CheckState ();
  213. CloseStartElement ();
  214. w.Write("<![CDATA[{0}]]>", text);
  215. }
  216. [MonoTODO]
  217. public override void WriteCharEntity (char ch)
  218. {
  219. throw new NotImplementedException ();
  220. }
  221. [MonoTODO]
  222. public override void WriteChars (char[] buffer, int index, int count)
  223. {
  224. throw new NotImplementedException ();
  225. }
  226. public override void WriteComment (string text)
  227. {
  228. if ((text.EndsWith("-")) || (text.IndexOf("-->") > 0)) {
  229. throw new ArgumentException ();
  230. }
  231. CheckState ();
  232. CloseStartElement ();
  233. w.Write ("<!--{0}-->", text);
  234. }
  235. [MonoTODO]
  236. public override void WriteDocType (string name, string pubid, string sysid, string subset)
  237. {
  238. throw new NotImplementedException ();
  239. }
  240. public override void WriteEndAttribute ()
  241. {
  242. if (!openAttribute)
  243. throw new InvalidOperationException("Token EndAttribute in state Start would result in an invalid XML document.");
  244. CheckState ();
  245. if (openXmlLang) {
  246. w.Write (xmlLang);
  247. openXmlLang = false;
  248. ((XmlTextWriterOpenElement)openElements.Peek()).XmlLang = xmlLang;
  249. }
  250. if (openXmlSpace)
  251. {
  252. w.Write (xmlSpace.ToString ().ToLower ());
  253. openXmlSpace = false;
  254. ((XmlTextWriterOpenElement)openElements.Peek()).XmlSpace = xmlSpace;
  255. }
  256. w.Write ("{0}", quoteChar);
  257. openAttribute = false;
  258. }
  259. [MonoTODO]
  260. public override void WriteEndDocument ()
  261. {
  262. throw new NotImplementedException ();
  263. }
  264. public override void WriteEndElement ()
  265. {
  266. if (openElements.Count == 0)
  267. throw new InvalidOperationException("There was no XML start tag open.");
  268. indentLevel--;
  269. CheckState ();
  270. if (openStartElement) {
  271. w.Write (" />");
  272. openElements.Pop ();
  273. openStartElement = false;
  274. }
  275. else {
  276. w.Write ("{0}</{1}>", indentFormatting, openElements.Pop ());
  277. namespaceManager.PopScope();
  278. }
  279. }
  280. [MonoTODO]
  281. public override void WriteEntityRef (string name)
  282. {
  283. throw new NotImplementedException ();
  284. }
  285. [MonoTODO]
  286. public override void WriteFullEndElement ()
  287. {
  288. throw new NotImplementedException ();
  289. }
  290. [MonoTODO]
  291. public override void WriteName (string name)
  292. {
  293. throw new NotImplementedException ();
  294. }
  295. [MonoTODO]
  296. public override void WriteNmToken (string name)
  297. {
  298. throw new NotImplementedException ();
  299. }
  300. public override void WriteProcessingInstruction (string name, string text)
  301. {
  302. if ((name == null) || (name == string.Empty) || (name.IndexOf("?>") > 0) || (text.IndexOf("?>") > 0)) {
  303. throw new ArgumentException ();
  304. }
  305. CheckState ();
  306. CloseStartElement ();
  307. w.Write ("{0}<?{1} {2}?>", indentFormatting, name, text);
  308. }
  309. [MonoTODO]
  310. public override void WriteQualifiedName (string localName, string ns)
  311. {
  312. throw new NotImplementedException ();
  313. }
  314. [MonoTODO]
  315. public override void WriteRaw (string data)
  316. {
  317. throw new NotImplementedException ();
  318. }
  319. [MonoTODO]
  320. public override void WriteRaw (char[] buffer, int index, int count)
  321. {
  322. throw new NotImplementedException ();
  323. }
  324. [MonoTODO("haven't tested namespaces on attributes code yet.")]
  325. public override void WriteStartAttribute (string prefix, string localName, string ns)
  326. {
  327. if ((prefix == "xml") && (localName == "lang"))
  328. openXmlLang = true;
  329. if ((prefix == "xml") && (localName == "space"))
  330. openXmlSpace = true;
  331. if ((prefix == "xmlns") && (localName == "xmlns"))
  332. 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.");
  333. CheckState ();
  334. if (prefix == null)
  335. prefix = String.Empty;
  336. if (ns == null)
  337. ns = String.Empty;
  338. string formatPrefix = "";
  339. if (ns != String.Empty)
  340. {
  341. string existingPrefix = namespaceManager.LookupPrefix (ns);
  342. if (prefix == String.Empty)
  343. prefix = existingPrefix;
  344. }
  345. if (prefix != String.Empty)
  346. {
  347. formatPrefix = prefix + ":";
  348. }
  349. w.Write (" {0}{1}={2}", formatPrefix, localName, quoteChar);
  350. openAttribute = true;
  351. ws = WriteState.Attribute;
  352. }
  353. public override void WriteStartDocument ()
  354. {
  355. WriteStartDocument ("");
  356. }
  357. public override void WriteStartDocument (bool standalone)
  358. {
  359. string standaloneFormatting;
  360. if (standalone == true)
  361. standaloneFormatting = String.Format (" standalone={0}yes{0}", quoteChar);
  362. else
  363. standaloneFormatting = String.Format (" standalone={0}no{0}", quoteChar);
  364. WriteStartDocument (standaloneFormatting);
  365. }
  366. private void WriteStartDocument (string standaloneFormatting)
  367. {
  368. if (documentStarted == true)
  369. throw new InvalidOperationException("WriteStartDocument should be the first call.");
  370. CheckState ();
  371. string encodingFormatting = "";
  372. if (!nullEncoding)
  373. encodingFormatting = String.Format (" encoding={0}{1}{0}", quoteChar, w.Encoding.HeaderName);
  374. w.Write("<?xml version={0}1.0{0}{1}{2}?>", quoteChar, encodingFormatting, standaloneFormatting);
  375. ws = WriteState.Prolog;
  376. }
  377. public override void WriteStartElement (string prefix, string localName, string ns)
  378. {
  379. if (!Namespaces && (((prefix != null) && (prefix != String.Empty))
  380. || ((ns != null) && (ns != String.Empty))))
  381. throw new ArgumentException ("Cannot set the namespace if Namespaces is 'false'.");
  382. WriteStartElementInternal (prefix, localName, ns);
  383. }
  384. protected override void WriteStartElementInternal (string prefix, string localName, string ns)
  385. {
  386. if (prefix == null)
  387. prefix = String.Empty;
  388. if (ns == null)
  389. ns = String.Empty;
  390. if ((prefix != String.Empty) && ((ns == null) || (ns == String.Empty)))
  391. throw new ArgumentException ("Cannot use a prefix with an empty namespace.");
  392. CheckState ();
  393. CloseStartElement ();
  394. string formatXmlns = "";
  395. string formatPrefix = "";
  396. if (ns != String.Empty)
  397. {
  398. string existingPrefix = namespaceManager.LookupPrefix (ns);
  399. if (prefix == String.Empty)
  400. prefix = existingPrefix;
  401. if (prefix != existingPrefix)
  402. formatXmlns = String.Format (" xmlns:{0}={1}{2}{1}", prefix, quoteChar, ns);
  403. else if (existingPrefix == String.Empty)
  404. formatXmlns = String.Format (" xmlns={0}{1}{0}", quoteChar, ns);
  405. }
  406. else if ((prefix == String.Empty) && (namespaceManager.LookupNamespace(prefix) != String.Empty)) {
  407. formatXmlns = String.Format (" xmlns={0}{0}", quoteChar);
  408. }
  409. if (prefix != String.Empty) {
  410. formatPrefix = prefix + ":";
  411. }
  412. w.Write ("{0}<{1}{2}{3}", indentFormatting, formatPrefix, localName, formatXmlns);
  413. openElements.Push (new XmlTextWriterOpenElement (formatPrefix + localName));
  414. ws = WriteState.Element;
  415. openStartElement = true;
  416. namespaceManager.PushScope ();
  417. namespaceManager.AddNamespace (prefix, ns);
  418. indentLevel++;
  419. }
  420. public override void WriteString (string text)
  421. {
  422. if (ws == WriteState.Prolog)
  423. throw new InvalidOperationException ("Token content in state Prolog would result in an invalid XML document.");
  424. if (text == null)
  425. text = String.Empty;
  426. if (text != String.Empty) {
  427. CheckState ();
  428. text = text.Replace ("&", "&amp;");
  429. text = text.Replace ("<", "&lt;");
  430. text = text.Replace (">", "&gt;");
  431. if (openAttribute) {
  432. if (quoteChar == '"')
  433. text = text.Replace ("\"", "&quot;");
  434. else
  435. text = text.Replace ("'", "&apos;");
  436. }
  437. if (!openAttribute)
  438. CloseStartElement ();
  439. if (!openXmlLang && !openXmlSpace)
  440. w.Write (text);
  441. else {
  442. if (openXmlLang)
  443. xmlLang = text;
  444. else {
  445. switch (text) {
  446. case "default":
  447. xmlSpace = XmlSpace.Default;
  448. break;
  449. case "preserve":
  450. xmlSpace = XmlSpace.Preserve;
  451. break;
  452. default:
  453. throw new ArgumentException ("'{0}' is an invalid xml:space value.");
  454. }
  455. }
  456. }
  457. }
  458. IndentingOverriden = true;
  459. }
  460. [MonoTODO]
  461. public override void WriteSurrogateCharEntity (char lowChar, char highChar)
  462. {
  463. throw new NotImplementedException ();
  464. }
  465. public override void WriteWhitespace (string ws)
  466. {
  467. foreach (char c in ws) {
  468. if ((c != ' ') && (c != '\t') && (c != '\r') && (c != '\n'))
  469. throw new ArgumentException ();
  470. }
  471. w.Write (ws);
  472. }
  473. #endregion
  474. }
  475. }