XmlTextWriter.cs 18 KB

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