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. w.Flush ();
  240. }
  241. public override string LookupPrefix (string ns)
  242. {
  243. string prefix = namespaceManager.LookupPrefix (ns);
  244. // XmlNamespaceManager has changed to return null when NSURI not found.
  245. // (Contradiction to the documentation.)
  246. //if (prefix == String.Empty)
  247. // prefix = null;
  248. return prefix;
  249. }
  250. private void UpdateIndentChars ()
  251. {
  252. indentChars = "";
  253. for (int i = 0; i < indentation; i++)
  254. indentChars += indentChar;
  255. }
  256. public override void WriteBase64 (byte[] buffer, int index, int count)
  257. {
  258. w.Write (Convert.ToBase64String (buffer, index, count));
  259. }
  260. [MonoTODO]
  261. public override void WriteBinHex (byte[] buffer, int index, int count)
  262. {
  263. throw new NotImplementedException ();
  264. }
  265. public override void WriteCData (string text)
  266. {
  267. if (text.IndexOf("]]>") > 0)
  268. throw new ArgumentException ();
  269. CheckState ();
  270. CloseStartElement ();
  271. w.Write("<![CDATA[{0}]]>", text);
  272. }
  273. public override void WriteCharEntity (char ch)
  274. {
  275. Int16 intCh = (Int16)ch;
  276. // Make sure the character is not in the surrogate pair
  277. // character range, 0xd800- 0xdfff
  278. if ((intCh >= -10240) && (intCh <= -8193))
  279. throw new ArgumentException ("Surrogate Pair is invalid.");
  280. w.Write("&#x{0:X};", intCh);
  281. }
  282. [MonoTODO]
  283. public override void WriteChars (char[] buffer, int index, int count)
  284. {
  285. throw new NotImplementedException ();
  286. }
  287. public override void WriteComment (string text)
  288. {
  289. if ((text.EndsWith("-")) || (text.IndexOf("-->") > 0)) {
  290. throw new ArgumentException ();
  291. }
  292. CheckState ();
  293. CloseStartElement ();
  294. w.Write ("<!--{0}-->", text);
  295. }
  296. public override void WriteDocType (string name, string pubid, string sysid, string subset)
  297. {
  298. if (name == null || name.Trim ().Length == 0)
  299. throw new ArgumentException ("Invalid DOCTYPE name", "name");
  300. w.Write ("<!DOCTYPE ");
  301. w.Write (name);
  302. if (pubid != null) {
  303. w.Write (String.Format (" PUBLIC {0}{1}{0} {0}{2}{0}", quoteChar, pubid, sysid));
  304. } else if (sysid != null) {
  305. w.Write (String.Format (" SYSTEM {0}{1}{0}", quoteChar, sysid));
  306. }
  307. if (subset != null)
  308. w.Write ("[" + subset + "]");
  309. w.Write('>');
  310. }
  311. public override void WriteEndAttribute ()
  312. {
  313. if (!openAttribute)
  314. throw new InvalidOperationException("Token EndAttribute in state Start would result in an invalid XML document.");
  315. CheckState ();
  316. if (openXmlLang) {
  317. w.Write (xmlLang);
  318. openXmlLang = false;
  319. ((XmlTextWriterOpenElement)openElements.Peek()).XmlLang = xmlLang;
  320. }
  321. if (openXmlSpace)
  322. {
  323. w.Write (xmlSpace.ToString ().ToLower ());
  324. openXmlSpace = false;
  325. ((XmlTextWriterOpenElement)openElements.Peek()).XmlSpace = xmlSpace;
  326. }
  327. w.Write ("{0}", quoteChar);
  328. openAttribute = false;
  329. }
  330. public override void WriteEndDocument ()
  331. {
  332. CloseOpenAttributeAndElements ();
  333. if (!hasRoot)
  334. throw new ArgumentException ("This document does not have a root element.");
  335. ws = WriteState.Start;
  336. hasRoot = false;
  337. }
  338. public override void WriteEndElement ()
  339. {
  340. WriteEndElementInternal (false);
  341. }
  342. private void WriteEndElementInternal (bool fullEndElement)
  343. {
  344. if (openElements.Count == 0)
  345. throw new InvalidOperationException("There was no XML start tag open.");
  346. indentLevel--;
  347. CheckState ();
  348. AddMissingElementXmlns ();
  349. if (openStartElement) {
  350. if (openAttribute)
  351. WriteEndAttribute ();
  352. if (fullEndElement)
  353. w.Write ("></{0}>", ((XmlTextWriterOpenElement)openElements.Peek ()).Name);
  354. else
  355. w.Write (" />");
  356. openElements.Pop ();
  357. openStartElement = false;
  358. } else {
  359. w.Write ("{0}</{1}>", indentFormatting, openElements.Pop ());
  360. }
  361. namespaceManager.PopScope();
  362. }
  363. [MonoTODO]
  364. public override void WriteEntityRef (string name)
  365. {
  366. throw new NotImplementedException ();
  367. }
  368. public override void WriteFullEndElement ()
  369. {
  370. WriteEndElementInternal (true);
  371. }
  372. private void CheckValidChars (string name, bool firstOnlyLetter)
  373. {
  374. foreach (char c in name) {
  375. if (XmlConvert.IsInvalid (c, firstOnlyLetter))
  376. throw new ArgumentException ("There is an invalid character: '" + c +
  377. "'", "name");
  378. }
  379. }
  380. public override void WriteName (string name)
  381. {
  382. CheckValidChars (name, true);
  383. w.Write (name);
  384. }
  385. public override void WriteNmToken (string name)
  386. {
  387. CheckValidChars (name, false);
  388. w.Write (name);
  389. }
  390. public override void WriteProcessingInstruction (string name, string text)
  391. {
  392. if ((name == null) || (name == string.Empty) || (name.IndexOf("?>") > 0) || (text.IndexOf("?>") > 0)) {
  393. throw new ArgumentException ();
  394. }
  395. CheckState ();
  396. CloseStartElement ();
  397. w.Write ("{0}<?{1} {2}?>", indentFormatting, name, text);
  398. }
  399. [MonoTODO]
  400. public override void WriteQualifiedName (string localName, string ns)
  401. {
  402. if (localName == null || localName == String.Empty)
  403. throw new ArgumentException ();
  404. CheckState ();
  405. w.Write ("{0}:{1}", ns, localName);
  406. }
  407. public override void WriteRaw (string data)
  408. {
  409. WriteStringInternal (data, false);
  410. }
  411. public override void WriteRaw (char[] buffer, int index, int count)
  412. {
  413. WriteStringInternal (new string (buffer, index, count), false);
  414. }
  415. public override void WriteStartAttribute (string prefix, string localName, string ns)
  416. {
  417. if ((prefix == "xml") && (localName == "lang"))
  418. openXmlLang = true;
  419. if ((prefix == "xml") && (localName == "space"))
  420. openXmlSpace = true;
  421. if ((prefix == "xmlns") && (localName.ToLower ().StartsWith ("xml")))
  422. 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);
  423. CheckState ();
  424. if (ws == WriteState.Content)
  425. throw new InvalidOperationException ("Token StartAttribute in state " + WriteState + " would result in an invalid XML document.");
  426. if (prefix == null)
  427. prefix = String.Empty;
  428. if (ns == null)
  429. ns = String.Empty;
  430. string formatPrefix = "";
  431. string formatSpace = "";
  432. if (ns != String.Empty)
  433. {
  434. string existingPrefix = namespaceManager.LookupPrefix (ns);
  435. if (prefix == String.Empty)
  436. prefix = (existingPrefix == null) ?
  437. String.Empty : existingPrefix;
  438. }
  439. if (prefix != String.Empty)
  440. {
  441. formatPrefix = prefix + ":";
  442. }
  443. if (openStartElement || attributeWrittenForElement)
  444. formatSpace = " ";
  445. // If already written, then break up.
  446. if (checkMultipleAttributes &&
  447. writtenAttributes.Contains (formatPrefix + localName))
  448. return;
  449. w.Write ("{0}{1}{2}={3}", formatSpace, formatPrefix, localName, quoteChar);
  450. if (checkMultipleAttributes)
  451. writtenAttributes.Add (formatPrefix + localName, formatPrefix + localName);
  452. openAttribute = true;
  453. attributeWrittenForElement = true;
  454. ws = WriteState.Attribute;
  455. if (prefix == String.Empty && localName == "xmlns") {
  456. if (namespaceManager.LookupNamespace (prefix) == null)
  457. namespaceManager.AddNamespace (prefix, ns);
  458. } else if (prefix == "xmlns") {
  459. if (namespaceManager.LookupNamespace (localName) == null)
  460. namespaceManager.AddNamespace (localName, ns);
  461. }
  462. }
  463. public override void WriteStartDocument ()
  464. {
  465. WriteStartDocument ("");
  466. }
  467. public override void WriteStartDocument (bool standalone)
  468. {
  469. string standaloneFormatting;
  470. if (standalone == true)
  471. standaloneFormatting = String.Format (" standalone={0}yes{0}", quoteChar);
  472. else
  473. standaloneFormatting = String.Format (" standalone={0}no{0}", quoteChar);
  474. WriteStartDocument (standaloneFormatting);
  475. }
  476. private void WriteStartDocument (string standaloneFormatting)
  477. {
  478. if (documentStarted == true)
  479. throw new InvalidOperationException("WriteStartDocument should be the first call.");
  480. if (hasRoot)
  481. throw new XmlException ("WriteStartDocument called twice.");
  482. hasRoot = true;
  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. CheckState ();
  502. CloseStartElement ();
  503. writtenAttributes.Clear ();
  504. checkMultipleAttributes = true;
  505. if (prefix == null)
  506. prefix = namespaceManager.LookupPrefix (ns);
  507. if (prefix == null)
  508. prefix = String.Empty;
  509. string formatPrefix = "";
  510. if(ns != null) {
  511. if (prefix != String.Empty)
  512. formatPrefix = prefix + ":";
  513. }
  514. w.Write ("{0}<{1}{2}", indentFormatting, formatPrefix, localName);
  515. openElements.Push (new XmlTextWriterOpenElement (formatPrefix + localName));
  516. ws = WriteState.Element;
  517. openStartElement = true;
  518. openElementNS = ns;
  519. openElementPrefix = prefix;
  520. namespaceManager.PushScope ();
  521. indentLevel++;
  522. }
  523. public override void WriteString (string text)
  524. {
  525. if (ws == WriteState.Prolog)
  526. throw new InvalidOperationException ("Token content in state Prolog would result in an invalid XML document.");
  527. WriteStringInternal (text, true);
  528. }
  529. private void WriteStringInternal (string text, bool entitize)
  530. {
  531. if (text == null)
  532. text = String.Empty;
  533. if (text != String.Empty)
  534. {
  535. CheckState ();
  536. if (entitize)
  537. {
  538. text = text.Replace ("&", "&amp;");
  539. text = text.Replace ("<", "&lt;");
  540. text = text.Replace (">", "&gt;");
  541. if (openAttribute)
  542. {
  543. if (quoteChar == '"')
  544. text = text.Replace ("\"", "&quot;");
  545. else
  546. text = text.Replace ("'", "&apos;");
  547. }
  548. }
  549. if (!openAttribute)
  550. {
  551. IndentingOverriden = true;
  552. CloseStartElement ();
  553. }
  554. if (!openXmlLang && !openXmlSpace)
  555. w.Write (text);
  556. else
  557. {
  558. if (openXmlLang)
  559. xmlLang = text;
  560. else
  561. {
  562. switch (text)
  563. {
  564. case "default":
  565. xmlSpace = XmlSpace.Default;
  566. break;
  567. case "preserve":
  568. xmlSpace = XmlSpace.Preserve;
  569. break;
  570. default:
  571. throw new ArgumentException ("'{0}' is an invalid xml:space value.");
  572. }
  573. }
  574. }
  575. }
  576. }
  577. [MonoTODO]
  578. public override void WriteSurrogateCharEntity (char lowChar, char highChar)
  579. {
  580. throw new NotImplementedException ();
  581. }
  582. public override void WriteWhitespace (string ws)
  583. {
  584. foreach (char c in ws) {
  585. if ((c != ' ') && (c != '\t') && (c != '\r') && (c != '\n'))
  586. throw new ArgumentException ();
  587. }
  588. w.Write (ws);
  589. }
  590. #endregion
  591. }
  592. }