XmlTextWriter.cs 16 KB

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