XmlTextWriter.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  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. w.Write ("{0}:{1}", ns, localName);
  407. }
  408. public override void WriteRaw (string data)
  409. {
  410. WriteStringInternal (data, false);
  411. }
  412. public override void WriteRaw (char[] buffer, int index, int count)
  413. {
  414. WriteStringInternal (new string (buffer, index, count), false);
  415. }
  416. public override void WriteStartAttribute (string prefix, string localName, string ns)
  417. {
  418. if ((prefix == "xml") && (localName == "lang"))
  419. openXmlLang = true;
  420. if ((prefix == "xml") && (localName == "space"))
  421. openXmlSpace = true;
  422. if ((prefix == "xmlns") && (localName.ToLower ().StartsWith ("xml")))
  423. 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);
  424. CheckState ();
  425. if (ws == WriteState.Content)
  426. throw new InvalidOperationException ("Token StartAttribute in state " + WriteState + " would result in an invalid XML document.");
  427. if (prefix == null)
  428. prefix = String.Empty;
  429. if (ns == null)
  430. ns = String.Empty;
  431. string formatPrefix = "";
  432. string formatSpace = "";
  433. if (ns != String.Empty)
  434. {
  435. string existingPrefix = namespaceManager.LookupPrefix (ns);
  436. if (prefix == String.Empty)
  437. prefix = (existingPrefix == null) ?
  438. String.Empty : existingPrefix;
  439. }
  440. if (prefix != String.Empty)
  441. {
  442. formatPrefix = prefix + ":";
  443. }
  444. if (openStartElement || attributeWrittenForElement)
  445. formatSpace = " ";
  446. // If already written, then break up.
  447. if (checkMultipleAttributes &&
  448. writtenAttributes.Contains (formatPrefix + localName))
  449. return;
  450. w.Write ("{0}{1}{2}={3}", formatSpace, formatPrefix, localName, quoteChar);
  451. if (checkMultipleAttributes)
  452. writtenAttributes.Add (formatPrefix + localName, formatPrefix + localName);
  453. openAttribute = true;
  454. attributeWrittenForElement = true;
  455. ws = WriteState.Attribute;
  456. if (prefix == String.Empty && localName == "xmlns") {
  457. if (namespaceManager.LookupNamespace (prefix) == null)
  458. namespaceManager.AddNamespace (prefix, ns);
  459. } else if (prefix == "xmlns") {
  460. if (namespaceManager.LookupNamespace (localName) == null)
  461. namespaceManager.AddNamespace (localName, ns);
  462. }
  463. }
  464. public override void WriteStartDocument ()
  465. {
  466. WriteStartDocument ("");
  467. }
  468. public override void WriteStartDocument (bool standalone)
  469. {
  470. string standaloneFormatting;
  471. if (standalone == true)
  472. standaloneFormatting = String.Format (" standalone={0}yes{0}", quoteChar);
  473. else
  474. standaloneFormatting = String.Format (" standalone={0}no{0}", quoteChar);
  475. WriteStartDocument (standaloneFormatting);
  476. }
  477. private void WriteStartDocument (string standaloneFormatting)
  478. {
  479. if (documentStarted == true)
  480. throw new InvalidOperationException("WriteStartDocument should be the first call.");
  481. if (hasRoot)
  482. throw new XmlException ("WriteStartDocument called twice.");
  483. CheckState ();
  484. string encodingFormatting = "";
  485. if (!nullEncoding)
  486. encodingFormatting = String.Format (" encoding={0}{1}{0}", quoteChar, w.Encoding.WebName);
  487. w.Write("<?xml version={0}1.0{0}{1}{2}?>", quoteChar, encodingFormatting, standaloneFormatting);
  488. ws = WriteState.Prolog;
  489. }
  490. public override void WriteStartElement (string prefix, string localName, string ns)
  491. {
  492. if (!Namespaces && (((prefix != null) && (prefix != String.Empty))
  493. || ((ns != null) && (ns != String.Empty))))
  494. throw new ArgumentException ("Cannot set the namespace if Namespaces is 'false'.");
  495. WriteStartElementInternal (prefix, localName, ns);
  496. }
  497. private void WriteStartElementInternal (string prefix, string localName, string ns)
  498. {
  499. if ((prefix != null && prefix != String.Empty) && ((ns == null) || (ns == String.Empty)))
  500. throw new ArgumentException ("Cannot use a prefix with an empty namespace.");
  501. hasRoot = true;
  502. CheckState ();
  503. CloseStartElement ();
  504. writtenAttributes.Clear ();
  505. checkMultipleAttributes = true;
  506. if (prefix == null)
  507. prefix = namespaceManager.LookupPrefix (ns);
  508. if (prefix == null)
  509. prefix = String.Empty;
  510. string formatPrefix = "";
  511. if(ns != null) {
  512. if (prefix != String.Empty)
  513. formatPrefix = prefix + ":";
  514. }
  515. w.Write ("{0}<{1}{2}", indentFormatting, formatPrefix, localName);
  516. openElements.Push (new XmlTextWriterOpenElement (formatPrefix + localName));
  517. ws = WriteState.Element;
  518. openStartElement = true;
  519. openElementNS = ns;
  520. openElementPrefix = prefix;
  521. namespaceManager.PushScope ();
  522. indentLevel++;
  523. }
  524. public override void WriteString (string text)
  525. {
  526. if (ws == WriteState.Prolog)
  527. throw new InvalidOperationException ("Token content in state Prolog would result in an invalid XML document.");
  528. WriteStringInternal (text, true);
  529. }
  530. private void WriteStringInternal (string text, bool entitize)
  531. {
  532. if (text == null)
  533. text = String.Empty;
  534. if (text != String.Empty)
  535. {
  536. CheckState ();
  537. if (entitize)
  538. {
  539. text = text.Replace ("&", "&amp;");
  540. text = text.Replace ("<", "&lt;");
  541. text = text.Replace (">", "&gt;");
  542. if (openAttribute)
  543. {
  544. if (quoteChar == '"')
  545. text = text.Replace ("\"", "&quot;");
  546. else
  547. text = text.Replace ("'", "&apos;");
  548. }
  549. }
  550. if (!openAttribute)
  551. {
  552. IndentingOverriden = true;
  553. CloseStartElement ();
  554. }
  555. if (!openXmlLang && !openXmlSpace)
  556. w.Write (text);
  557. else
  558. {
  559. if (openXmlLang)
  560. xmlLang = text;
  561. else
  562. {
  563. switch (text)
  564. {
  565. case "default":
  566. xmlSpace = XmlSpace.Default;
  567. break;
  568. case "preserve":
  569. xmlSpace = XmlSpace.Preserve;
  570. break;
  571. default:
  572. throw new ArgumentException ("'{0}' is an invalid xml:space value.");
  573. }
  574. }
  575. }
  576. }
  577. }
  578. [MonoTODO]
  579. public override void WriteSurrogateCharEntity (char lowChar, char highChar)
  580. {
  581. throw new NotImplementedException ();
  582. }
  583. public override void WriteWhitespace (string ws)
  584. {
  585. foreach (char c in ws) {
  586. if ((c != ' ') && (c != '\t') && (c != '\r') && (c != '\n'))
  587. throw new ArgumentException ();
  588. }
  589. w.Write (ws);
  590. }
  591. #endregion
  592. }
  593. }