XmlTextWriter.cs 16 KB

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