XmlTextWriter.cs 17 KB

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