XmlTextWriter.cs 17 KB

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