XmlTextWriter.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. //
  2. // System.Xml.XmlTextWriter
  3. //
  4. // Author:
  5. // Kral Ferch <[email protected]>
  6. // Atsushi Enomoto <[email protected]>
  7. //
  8. // (C) 2002 Kral Ferch
  9. // (C) 2003 Atsushi Enomoto
  10. //
  11. using System;
  12. using System.Collections;
  13. using System.IO;
  14. using System.Text;
  15. namespace System.Xml
  16. {
  17. public class XmlTextWriter : XmlWriter
  18. {
  19. #region Fields
  20. const string XmlnsNamespace = "http://www.w3.org/2000/xmlns/";
  21. WriteState ws = WriteState.Start;
  22. TextWriter w;
  23. bool nullEncoding = false;
  24. bool openWriter = true;
  25. bool openStartElement = 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 newAttributeNamespaces = new Hashtable ();
  47. Hashtable userWrittenNamespaces = new Hashtable ();
  48. StringBuilder cachedStringBuilder;
  49. XmlNamespaceManager namespaceManager = new XmlNamespaceManager (new NameTable ());
  50. string savingAttributeValue = String.Empty;
  51. bool saveAttributeValue;
  52. string savedAttributePrefix;
  53. bool shouldAddSavedNsToManager;
  54. bool shouldCheckElementXmlns;
  55. #endregion
  56. #region Constructors
  57. public XmlTextWriter (TextWriter w) : base ()
  58. {
  59. this.w = w;
  60. nullEncoding = (w.Encoding == null);
  61. StreamWriter sw = w as StreamWriter;
  62. if (sw != null)
  63. baseStream = ((StreamWriter)w).BaseStream;
  64. }
  65. public XmlTextWriter (Stream w, Encoding encoding) : base ()
  66. {
  67. if (encoding == null) {
  68. nullEncoding = true;
  69. this.w = new StreamWriter (w);
  70. } else
  71. this.w = new StreamWriter(w, encoding);
  72. baseStream = w;
  73. }
  74. public XmlTextWriter (string filename, Encoding encoding) :
  75. this (new FileStream (filename, FileMode.Create, FileAccess.Write, FileShare.None), encoding)
  76. {
  77. }
  78. #endregion
  79. #region Properties
  80. public Stream BaseStream {
  81. get { return baseStream; }
  82. }
  83. public Formatting Formatting {
  84. get { return formatting; }
  85. set { formatting = value; }
  86. }
  87. private bool IndentingOverriden
  88. {
  89. get {
  90. if (openElements.Count == 0)
  91. return false;
  92. else
  93. return (((XmlTextWriterOpenElement)openElements.Peek()).IndentingOverriden);
  94. }
  95. set {
  96. if (openElements.Count > 0)
  97. ((XmlTextWriterOpenElement)openElements.Peek()).IndentingOverriden = value;
  98. }
  99. }
  100. public int Indentation {
  101. get { return indentation; }
  102. set {
  103. indentation = value;
  104. UpdateIndentChars ();
  105. }
  106. }
  107. public char IndentChar {
  108. get { return indentChar; }
  109. set {
  110. indentChar = value;
  111. UpdateIndentChars ();
  112. }
  113. }
  114. public bool Namespaces {
  115. get { return namespaces; }
  116. set {
  117. if (ws != WriteState.Start)
  118. throw new InvalidOperationException ("NotInWriteState.");
  119. namespaces = value;
  120. }
  121. }
  122. public char QuoteChar {
  123. get { return quoteChar; }
  124. set {
  125. if ((value != '\'') && (value != '\"'))
  126. throw new ArgumentException ("This is an invalid XML attribute quote character. Valid attribute quote characters are ' and \".");
  127. quoteChar = value;
  128. }
  129. }
  130. public override WriteState WriteState {
  131. get { return ws; }
  132. }
  133. public override string XmlLang {
  134. get {
  135. string xmlLang = null;
  136. int i;
  137. for (i = 0; i < openElements.Count; i++)
  138. {
  139. xmlLang = ((XmlTextWriterOpenElement)openElements.ToArray().GetValue(i)).XmlLang;
  140. if (xmlLang != null)
  141. break;
  142. }
  143. return xmlLang;
  144. }
  145. }
  146. public override XmlSpace XmlSpace {
  147. get {
  148. XmlSpace xmlSpace = XmlSpace.None;
  149. int i;
  150. for (i = 0; i < openElements.Count; i++)
  151. {
  152. xmlSpace = ((XmlTextWriterOpenElement)openElements.ToArray().GetValue(i)).XmlSpace;
  153. if (xmlSpace != XmlSpace.None)
  154. break;
  155. }
  156. return xmlSpace;
  157. }
  158. }
  159. #endregion
  160. #region Methods
  161. private void AddMissingElementXmlns ()
  162. {
  163. // output namespace declaration if not exist.
  164. string prefix = openElementPrefix;
  165. string ns = openElementNS;
  166. openElementPrefix = null;
  167. openElementNS = null;
  168. // LAMESPEC: If prefix was already assigned another nsuri, then this element's nsuri goes away!
  169. if (this.shouldCheckElementXmlns) {
  170. string formatXmlns = String.Empty;
  171. if (userWrittenNamespaces [prefix] == null) {
  172. if (prefix != string.Empty) {
  173. w.Write (" xmlns:");
  174. w.Write (prefix);
  175. w.Write ('=');
  176. w.Write (quoteChar);
  177. w.Write (EscapeString (ns, false));
  178. w.Write (quoteChar);
  179. }
  180. else {
  181. w.Write (" xmlns=");
  182. w.Write (quoteChar);
  183. w.Write (EscapeString (ns, false));
  184. w.Write (quoteChar);
  185. }
  186. }
  187. shouldCheckElementXmlns = false;
  188. }
  189. if (newAttributeNamespaces.Count > 0)
  190. {
  191. foreach (DictionaryEntry ent in newAttributeNamespaces)
  192. {
  193. string ans = (string) ent.Value;
  194. string aprefix = (string) ent.Key;
  195. if (namespaceManager.LookupNamespace (aprefix) == ans)
  196. continue;
  197. w.Write (" xmlns:");
  198. w.Write (aprefix);
  199. w.Write ('=');
  200. w.Write (quoteChar);
  201. w.Write (EscapeString (ans, false));
  202. w.Write (quoteChar);
  203. }
  204. newAttributeNamespaces.Clear ();
  205. }
  206. }
  207. private void CheckState ()
  208. {
  209. if (!openWriter) {
  210. throw new InvalidOperationException ("The Writer is closed.");
  211. }
  212. if ((documentStarted == true) && (formatting == Formatting.Indented) && (!IndentingOverriden)) {
  213. indentFormatting = w.NewLine;
  214. if (indentLevel > 0) {
  215. for (int i = 0; i < indentLevel; i++)
  216. indentFormatting += indentChars;
  217. }
  218. }
  219. else
  220. indentFormatting = "";
  221. documentStarted = true;
  222. }
  223. public override void Close ()
  224. {
  225. CloseOpenAttributeAndElements ();
  226. w.Close();
  227. ws = WriteState.Closed;
  228. openWriter = false;
  229. }
  230. private void CloseOpenAttributeAndElements ()
  231. {
  232. if (openAttribute)
  233. WriteEndAttribute ();
  234. while (openElements.Count > 0) {
  235. WriteEndElement();
  236. }
  237. }
  238. private void CloseStartElement ()
  239. {
  240. if (!openStartElement)
  241. return;
  242. AddMissingElementXmlns ();
  243. w.Write (">");
  244. ws = WriteState.Content;
  245. openStartElement = false;
  246. attributeWrittenForElement = false;
  247. newAttributeNamespaces.Clear ();
  248. userWrittenNamespaces.Clear ();
  249. }
  250. public override void Flush ()
  251. {
  252. w.Flush ();
  253. }
  254. public override string LookupPrefix (string ns)
  255. {
  256. if (ns == null || ns == String.Empty)
  257. throw new ArgumentException ("The Namespace cannot be empty.");
  258. string prefix = namespaceManager.LookupPrefix (ns);
  259. // XmlNamespaceManager has changed to return null when NSURI not found.
  260. // (Contradiction to the ECMA documentation.)
  261. return prefix;
  262. }
  263. private void UpdateIndentChars ()
  264. {
  265. indentChars = "";
  266. for (int i = 0; i < indentation; i++)
  267. indentChars += indentChar;
  268. }
  269. public override void WriteBase64 (byte[] buffer, int index, int count)
  270. {
  271. CheckState ();
  272. if (!openAttribute) {
  273. IndentingOverriden = true;
  274. CloseStartElement ();
  275. }
  276. w.Write (Convert.ToBase64String (buffer, index, count));
  277. }
  278. public override void WriteBinHex (byte[] buffer, int index, int count)
  279. {
  280. CheckState ();
  281. if (!openAttribute) {
  282. IndentingOverriden = true;
  283. CloseStartElement ();
  284. }
  285. if (index < 0)
  286. throw new ArgumentOutOfRangeException ("index", index, "index must be non negative integer.");
  287. if (count < 0)
  288. throw new ArgumentOutOfRangeException ("count", count, "count must be non negative integer.");
  289. if (buffer.Length < index + count)
  290. throw new ArgumentOutOfRangeException ("index and count must be smaller than the length of the buffer.");
  291. for (int i = index; i < count; i++) {
  292. int val = buffer [i];
  293. int high = val >> 4;
  294. int low = val & 15;
  295. if (high > 9)
  296. w.Write ((char) (high + 55));
  297. else
  298. w.Write ((char) (high + 0x30));
  299. if (low > 9)
  300. w.Write ((char) (low + 55));
  301. else
  302. w.Write ((char) (low + 0x30));
  303. }
  304. }
  305. public override void WriteCData (string text)
  306. {
  307. if (text.IndexOf ("]]>") >= 0)
  308. throw new ArgumentException ();
  309. CheckState ();
  310. CloseStartElement ();
  311. w.Write ("<![CDATA[");
  312. w.Write (text);
  313. w.Write ("]]>");
  314. }
  315. public override void WriteCharEntity (char ch)
  316. {
  317. Int16 intCh = (Int16)ch;
  318. // Make sure the character is not in the surrogate pair
  319. // character range, 0xd800- 0xdfff
  320. if ((intCh >= -10240) && (intCh <= -8193))
  321. throw new ArgumentException ("Surrogate Pair is invalid.");
  322. w.Write("&#x{0:X};", intCh);
  323. }
  324. public override void WriteChars (char[] buffer, int index, int count)
  325. {
  326. CheckState ();
  327. if (!openAttribute) {
  328. IndentingOverriden = true;
  329. CloseStartElement ();
  330. }
  331. w.Write (buffer, index, count);
  332. }
  333. public override void WriteComment (string text)
  334. {
  335. if ((text.EndsWith("-")) || (text.IndexOf("--") > 0)) {
  336. throw new ArgumentException ();
  337. }
  338. CheckState ();
  339. CloseStartElement ();
  340. w.Write ("<!--");
  341. w.Write (text);
  342. w.Write ("-->");
  343. }
  344. public override void WriteDocType (string name, string pubid, string sysid, string subset)
  345. {
  346. if (name == null || name.Trim (XmlChar.WhitespaceChars).Length == 0)
  347. throw new ArgumentException ("Invalid DOCTYPE name", "name");
  348. if (ws == WriteState.Prolog && formatting == Formatting.Indented)
  349. w.WriteLine ();
  350. w.Write ("<!DOCTYPE ");
  351. w.Write (name);
  352. if (pubid != null) {
  353. w.Write (" PUBLIC ");
  354. w.Write (quoteChar);
  355. w.Write (pubid);
  356. w.Write (quoteChar);
  357. w.Write (' ');
  358. w.Write (quoteChar);
  359. w.Write (sysid);
  360. w.Write (quoteChar);
  361. } else if (sysid != null) {
  362. w.Write (" SYSTEM ");
  363. w.Write (quoteChar);
  364. w.Write (sysid);
  365. w.Write (quoteChar);
  366. }
  367. if (subset != null) {
  368. w.Write ('[');
  369. w.Write (subset);
  370. w.Write (']');
  371. }
  372. w.Write('>');
  373. }
  374. public override void WriteEndAttribute ()
  375. {
  376. if (!openAttribute)
  377. throw new InvalidOperationException("Token EndAttribute in state Start would result in an invalid XML document.");
  378. CheckState ();
  379. if (openXmlLang) {
  380. w.Write (xmlLang);
  381. openXmlLang = false;
  382. ((XmlTextWriterOpenElement)openElements.Peek()).XmlLang = xmlLang;
  383. }
  384. if (openXmlSpace)
  385. {
  386. w.Write (xmlSpace.ToString ().ToLower ());
  387. openXmlSpace = false;
  388. ((XmlTextWriterOpenElement)openElements.Peek()).XmlSpace = xmlSpace;
  389. }
  390. w.Write (quoteChar);
  391. openAttribute = false;
  392. if (saveAttributeValue) {
  393. if (savedAttributePrefix.Length > 0 && savingAttributeValue.Length == 0)
  394. throw new ArgumentException ("Cannot use prefix with an empty namespace.");
  395. // add namespace
  396. if (shouldAddSavedNsToManager) // not OLD one
  397. namespaceManager.AddNamespace (savedAttributePrefix, savingAttributeValue);
  398. userWrittenNamespaces [savedAttributePrefix] = savingAttributeValue;
  399. saveAttributeValue = false;
  400. savedAttributePrefix = String.Empty;
  401. savingAttributeValue = String.Empty;
  402. }
  403. }
  404. public override void WriteEndDocument ()
  405. {
  406. CloseOpenAttributeAndElements ();
  407. if (!hasRoot)
  408. throw new ArgumentException ("This document does not have a root element.");
  409. ws = WriteState.Start;
  410. hasRoot = false;
  411. }
  412. public override void WriteEndElement ()
  413. {
  414. WriteEndElementInternal (false);
  415. }
  416. private void WriteEndElementInternal (bool fullEndElement)
  417. {
  418. if (openElements.Count == 0)
  419. throw new InvalidOperationException("There was no XML start tag open.");
  420. if (openAttribute)
  421. WriteEndAttribute ();
  422. indentLevel--;
  423. CheckState ();
  424. AddMissingElementXmlns ();
  425. if (openStartElement) {
  426. if (openAttribute)
  427. WriteEndAttribute ();
  428. if (fullEndElement) {
  429. w.Write ('>');
  430. w.Write (indentFormatting);
  431. w.Write ("</");
  432. XmlTextWriterOpenElement el = (XmlTextWriterOpenElement) openElements.Peek ();
  433. if (el.Prefix != String.Empty) {
  434. w.Write (el.Prefix);
  435. w.Write (':');
  436. }
  437. w.Write (el.LocalName);
  438. w.Write ('>');
  439. } else
  440. w.Write (" />");
  441. openElements.Pop ();
  442. openStartElement = false;
  443. } else {
  444. w.Write (indentFormatting);
  445. w.Write ("</");
  446. XmlTextWriterOpenElement el = (XmlTextWriterOpenElement) openElements.Pop ();
  447. if (el.Prefix != String.Empty) {
  448. w.Write (el.Prefix);
  449. w.Write (':');
  450. }
  451. w.Write (el.LocalName);
  452. w.Write ('>');
  453. }
  454. namespaceManager.PopScope();
  455. }
  456. public override void WriteEntityRef (string name)
  457. {
  458. WriteRaw ("&");
  459. WriteStringInternal (name, true);
  460. WriteRaw (";");
  461. }
  462. public override void WriteFullEndElement ()
  463. {
  464. WriteEndElementInternal (true);
  465. }
  466. public override void WriteName (string name)
  467. {
  468. if (!XmlChar.IsName (name))
  469. throw new ArgumentException ("There is an invalid character: '" + name [0] +
  470. "'", "name");
  471. w.Write (name);
  472. }
  473. public override void WriteNmToken (string name)
  474. {
  475. if (!XmlChar.IsNmToken (name))
  476. throw new ArgumentException ("There is an invalid character: '" + name [0] +
  477. "'", "name");
  478. w.Write (name);
  479. }
  480. // LAMESPEC: It should reject such name that starts with "x" "m" "l" by XML specification, but
  481. // in fact it is used to write XmlDeclaration in WriteNode() (and it is inevitable since
  482. // WriteStartDocument() cannot specify encoding, while WriteNode() can write it).
  483. public override void WriteProcessingInstruction (string name, string text)
  484. {
  485. if ((name == null) || (name == string.Empty))
  486. throw new ArgumentException ();
  487. if (!XmlChar.IsName (name))
  488. throw new ArgumentException ("Invalid processing instruction name.");
  489. if ((text.IndexOf("?>") > 0))
  490. throw new ArgumentException ("Processing instruction cannot contain \"?>\" as its value.");
  491. CheckState ();
  492. CloseStartElement ();
  493. w.Write (indentFormatting);
  494. w.Write ("<?");
  495. w.Write (name);
  496. w.Write (' ');
  497. w.Write (text);
  498. w.Write ("?>");
  499. }
  500. public override void WriteQualifiedName (string localName, string ns)
  501. {
  502. if (localName == null || localName == String.Empty)
  503. throw new ArgumentException ();
  504. CheckState ();
  505. if (!openAttribute)
  506. CloseStartElement ();
  507. w.Write (namespaceManager.LookupPrefix (ns));
  508. w.Write (':');
  509. w.Write (localName);
  510. }
  511. public override void WriteRaw (string data)
  512. {
  513. WriteStringInternal (data, false);
  514. }
  515. public override void WriteRaw (char[] buffer, int index, int count)
  516. {
  517. // WriteRawInternal (new string (buffer, index, count));
  518. WriteStringInternal (new string (buffer, index, count), false);
  519. }
  520. public override void WriteStartAttribute (string prefix, string localName, string ns)
  521. {
  522. if (prefix == "xml") {
  523. // MS.NET looks to allow other names than
  524. // lang and space (e.g. xml:link, xml:hack).
  525. ns = XmlNamespaceManager.XmlnsXml;
  526. if (localName == "lang")
  527. openXmlLang = true;
  528. else if (localName == "space")
  529. openXmlSpace = true;
  530. }
  531. if (prefix == null)
  532. prefix = String.Empty;
  533. if (prefix.Length > 0 && (ns == null || ns.Length == 0))
  534. if (prefix != "xmlns")
  535. throw new ArgumentException ("Cannot use prefix with an empty namespace.");
  536. if ((prefix == "xmlns") && (localName.ToLower ().StartsWith ("xml")))
  537. 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);
  538. // Note that null namespace with "xmlns" are allowed.
  539. #if NET_1_0
  540. if ((prefix == "xmlns" || localName == "xmlns" && prefix == String.Empty) && ns != XmlnsNamespace)
  541. #else
  542. if ((prefix == "xmlns" || localName == "xmlns" && prefix == String.Empty) && ns != null && ns != XmlnsNamespace)
  543. #endif
  544. throw new ArgumentException (String.Format ("The 'xmlns' attribute is bound to the reserved namespace '{0}'", XmlnsNamespace));
  545. CheckState ();
  546. if (ws == WriteState.Content)
  547. throw new InvalidOperationException ("Token StartAttribute in state " + WriteState + " would result in an invalid XML document.");
  548. if (prefix == null)
  549. prefix = String.Empty;
  550. if (ns == null)
  551. ns = String.Empty;
  552. string formatPrefix = "";
  553. string formatSpace = "";
  554. if (ns != String.Empty && prefix != "xmlns") {
  555. string existingPrefix = namespaceManager.LookupPrefix (ns);
  556. if (existingPrefix == null || existingPrefix == "") {
  557. bool createPrefix = false;
  558. if (prefix == "")
  559. createPrefix = true;
  560. else {
  561. string existingNs = namespaceManager.LookupNamespace (prefix);
  562. if (existingNs != null) {
  563. namespaceManager.RemoveNamespace (prefix, existingNs);
  564. if (namespaceManager.LookupNamespace (prefix) != existingNs) {
  565. createPrefix = true;
  566. namespaceManager.AddNamespace (prefix, existingNs);
  567. }
  568. }
  569. }
  570. if (createPrefix)
  571. prefix = "d" + indentLevel + "p" + (newAttributeNamespaces.Count + 1);
  572. // check if prefix exists. If yes - check if namespace is the same.
  573. if (newAttributeNamespaces [prefix] == null)
  574. newAttributeNamespaces.Add (prefix, ns);
  575. else if (!newAttributeNamespaces [prefix].Equals (ns))
  576. throw new ArgumentException ("Duplicate prefix with different namespace");
  577. }
  578. if (prefix == String.Empty && ns != XmlnsNamespace)
  579. prefix = (existingPrefix == null) ?
  580. String.Empty : existingPrefix;
  581. }
  582. if (prefix != String.Empty)
  583. {
  584. formatPrefix = prefix + ":";
  585. }
  586. if (openStartElement || attributeWrittenForElement)
  587. formatSpace = " ";
  588. w.Write (formatSpace);
  589. w.Write (formatPrefix);
  590. w.Write (localName);
  591. w.Write ('=');
  592. w.Write (quoteChar);
  593. openAttribute = true;
  594. attributeWrittenForElement = true;
  595. ws = WriteState.Attribute;
  596. if (prefix == "xmlns" || prefix == String.Empty && localName == "xmlns") {
  597. if (prefix != openElementPrefix || openElementNS == null)
  598. shouldAddSavedNsToManager = true;
  599. saveAttributeValue = true;
  600. savedAttributePrefix = (prefix == "xmlns") ? localName : String.Empty;
  601. savingAttributeValue = String.Empty;
  602. }
  603. }
  604. public override void WriteStartDocument ()
  605. {
  606. WriteStartDocument ("");
  607. }
  608. public override void WriteStartDocument (bool standalone)
  609. {
  610. string standaloneFormatting;
  611. if (standalone == true)
  612. standaloneFormatting = String.Format (" standalone={0}yes{0}", quoteChar);
  613. else
  614. standaloneFormatting = String.Format (" standalone={0}no{0}", quoteChar);
  615. WriteStartDocument (standaloneFormatting);
  616. }
  617. private void WriteStartDocument (string standaloneFormatting)
  618. {
  619. if (documentStarted == true)
  620. throw new InvalidOperationException("WriteStartDocument should be the first call.");
  621. if (hasRoot)
  622. throw new XmlException ("WriteStartDocument called twice.");
  623. CheckState ();
  624. string encodingFormatting = "";
  625. if (!nullEncoding)
  626. encodingFormatting = String.Format (" encoding={0}{1}{0}", quoteChar, w.Encoding.WebName);
  627. w.Write("<?xml version={0}1.0{0}{1}{2}?>", quoteChar, encodingFormatting, standaloneFormatting);
  628. ws = WriteState.Prolog;
  629. }
  630. public override void WriteStartElement (string prefix, string localName, string ns)
  631. {
  632. if (!Namespaces && (((prefix != null) && (prefix != String.Empty))
  633. || ((ns != null) && (ns != String.Empty))))
  634. throw new ArgumentException ("Cannot set the namespace if Namespaces is 'false'.");
  635. if ((prefix != null && prefix != String.Empty) && ((ns == null) || (ns == String.Empty)))
  636. throw new ArgumentException ("Cannot use a prefix with an empty namespace.");
  637. // ignore non-namespaced node's prefix.
  638. if (ns == null || ns == String.Empty)
  639. prefix = String.Empty;
  640. WriteStartElementInternal (prefix, localName, ns);
  641. }
  642. private void WriteStartElementInternal (string prefix, string localName, string ns)
  643. {
  644. hasRoot = true;
  645. CheckState ();
  646. CloseStartElement ();
  647. newAttributeNamespaces.Clear ();
  648. userWrittenNamespaces.Clear ();
  649. shouldCheckElementXmlns = false;
  650. if (prefix == null && ns != null)
  651. prefix = namespaceManager.LookupPrefix (ns);
  652. if (prefix == null)
  653. prefix = String.Empty;
  654. w.Write (indentFormatting);
  655. w.Write ('<');
  656. if (prefix != String.Empty) {
  657. w.Write (prefix);
  658. w.Write (':');
  659. }
  660. w.Write (localName);
  661. openElements.Push (new XmlTextWriterOpenElement (prefix, localName));
  662. ws = WriteState.Element;
  663. openStartElement = true;
  664. openElementNS = ns;
  665. openElementPrefix = prefix;
  666. namespaceManager.PushScope ();
  667. indentLevel++;
  668. if (ns != null) {
  669. if (ns.Length > 0) {
  670. string existing = LookupPrefix (ns);
  671. if (existing != prefix) {
  672. shouldCheckElementXmlns = true;
  673. namespaceManager.AddNamespace (prefix, ns);
  674. }
  675. } else {
  676. if (ns != namespaceManager.DefaultNamespace) {
  677. shouldCheckElementXmlns = true;
  678. namespaceManager.AddNamespace ("", ns);
  679. }
  680. }
  681. }
  682. }
  683. public override void WriteString (string text)
  684. {
  685. if (ws == WriteState.Prolog)
  686. throw new InvalidOperationException ("Token content in state Prolog would result in an invalid XML document.");
  687. WriteStringInternal (text, true);
  688. // MS.NET (1.0) saves attribute value only at WriteString.
  689. if (saveAttributeValue)
  690. // In most cases it will be called one time, so simply use string + string.
  691. savingAttributeValue += text;
  692. }
  693. string [] replacements = new string [] {
  694. "&amp;", "&lt;", "&gt;", "&quot;", "&apos;",
  695. "&#xD;", "&#xA;"};
  696. private string EscapeString (string source, bool skipQuotations)
  697. {
  698. int start = 0;
  699. int pos = 0;
  700. int count = source.Length;
  701. for (int i = 0; i < count; i++) {
  702. switch (source [i]) {
  703. case '&': pos = 0; break;
  704. case '<': pos = 1; break;
  705. case '>': pos = 2; break;
  706. case '\"':
  707. if (skipQuotations) continue;
  708. if (QuoteChar == '\'') continue;
  709. pos = 3; break;
  710. case '\'':
  711. if (skipQuotations) continue;
  712. if (QuoteChar == '\"') continue;
  713. pos = 4; break;
  714. case '\r':
  715. if (skipQuotations) continue;
  716. pos = 5; break;
  717. case '\n':
  718. if (skipQuotations) continue;
  719. pos = 6; break;
  720. default:
  721. continue;
  722. }
  723. if (cachedStringBuilder == null)
  724. cachedStringBuilder = new StringBuilder ();
  725. cachedStringBuilder.Append (source.Substring (start, i - start));
  726. cachedStringBuilder.Append (replacements [pos]);
  727. start = i + 1;
  728. }
  729. if (start == 0)
  730. return source;
  731. else if (start < count)
  732. cachedStringBuilder.Append (source.Substring (start, count - start));
  733. string s = cachedStringBuilder.ToString ();
  734. cachedStringBuilder.Length = 0;
  735. return s;
  736. }
  737. private void WriteStringInternal (string text, bool entitize)
  738. {
  739. if (text == null)
  740. text = String.Empty;
  741. if (text != String.Empty) {
  742. CheckState ();
  743. if (entitize)
  744. text = EscapeString (text, !openAttribute);
  745. if (!openAttribute)
  746. {
  747. IndentingOverriden = true;
  748. CloseStartElement ();
  749. }
  750. if (!openXmlLang && !openXmlSpace)
  751. w.Write (text);
  752. else
  753. {
  754. if (openXmlLang)
  755. xmlLang = text;
  756. else
  757. {
  758. switch (text)
  759. {
  760. case "default":
  761. xmlSpace = XmlSpace.Default;
  762. break;
  763. case "preserve":
  764. xmlSpace = XmlSpace.Preserve;
  765. break;
  766. default:
  767. throw new ArgumentException ("'{0}' is an invalid xml:space value.");
  768. }
  769. }
  770. }
  771. }
  772. }
  773. public override void WriteSurrogateCharEntity (char lowChar, char highChar)
  774. {
  775. if (lowChar < '\uDC00' || lowChar > '\uDFFF' ||
  776. highChar < '\uD800' || highChar > '\uDBFF')
  777. throw new ArgumentException ("Invalid (low, high) pair of characters was specified.");
  778. CheckState ();
  779. if (!openAttribute) {
  780. IndentingOverriden = true;
  781. CloseStartElement ();
  782. }
  783. w.Write ("&#x");
  784. w.Write (((int) ((highChar - 0xD800) * 0x400 + (lowChar - 0xDC00) + 0x10000)).ToString ("X"));
  785. w.Write (';');
  786. }
  787. public override void WriteWhitespace (string ws)
  788. {
  789. if (!XmlChar.IsWhitespace (ws))
  790. throw new ArgumentException ("Invalid Whitespace");
  791. CheckState ();
  792. if (!openAttribute) {
  793. IndentingOverriden = true;
  794. CloseStartElement ();
  795. }
  796. w.Write (ws);
  797. }
  798. #endregion
  799. }
  800. }