XmlTextWriter.cs 24 KB

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