XmlTextWriter.cs 17 KB

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