XmlTextWriter.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  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. int openElementCount;
  32. Formatting formatting = Formatting.None;
  33. int indentation = 2;
  34. char indentChar = ' ';
  35. string indentChars = " ";
  36. char quoteChar = '\"';
  37. int indentLevel = 0;
  38. string indentFormatting;
  39. Stream baseStream = null;
  40. string xmlLang = null;
  41. XmlSpace xmlSpace = XmlSpace.None;
  42. bool openXmlLang = false;
  43. bool openXmlSpace = false;
  44. string openElementPrefix;
  45. string openElementNS;
  46. bool hasRoot = false;
  47. Hashtable newAttributeNamespaces = new Hashtable ();
  48. Hashtable userWrittenNamespaces = new Hashtable ();
  49. StringBuilder cachedStringBuilder;
  50. XmlNamespaceManager namespaceManager = new XmlNamespaceManager (new NameTable ());
  51. string savingAttributeValue = String.Empty;
  52. bool saveAttributeValue;
  53. string savedAttributePrefix;
  54. bool shouldAddSavedNsToManager;
  55. bool shouldCheckElementXmlns;
  56. #endregion
  57. #region Constructors
  58. public XmlTextWriter (TextWriter w) : base ()
  59. {
  60. this.w = w;
  61. nullEncoding = (w.Encoding == null);
  62. StreamWriter sw = w as StreamWriter;
  63. if (sw != null)
  64. baseStream = sw.BaseStream;
  65. }
  66. public XmlTextWriter (Stream w, Encoding encoding) : base ()
  67. {
  68. if (encoding == null) {
  69. nullEncoding = true;
  70. this.w = new StreamWriter (w);
  71. } else
  72. this.w = new StreamWriter (w, encoding);
  73. baseStream = w;
  74. }
  75. public XmlTextWriter (string filename, Encoding encoding) :
  76. this (new FileStream (filename, FileMode.Create, FileAccess.Write, FileShare.None), encoding)
  77. {
  78. }
  79. #endregion
  80. #region Properties
  81. public Stream BaseStream {
  82. get { return baseStream; }
  83. }
  84. public Formatting Formatting {
  85. get { return formatting; }
  86. set { formatting = value; }
  87. }
  88. private bool IndentingOverriden
  89. {
  90. get {
  91. if (openElementCount == 0)
  92. return false;
  93. else
  94. return ((XmlTextWriterOpenElement)
  95. openElements [openElementCount - 1]).IndentingOverriden;
  96. }
  97. set {
  98. if (openElementCount > 0)
  99. ((XmlTextWriterOpenElement) openElements [openElementCount - 1]).IndentingOverriden = value;
  100. }
  101. }
  102. public int Indentation {
  103. get { return indentation; }
  104. set {
  105. indentation = value;
  106. UpdateIndentChars ();
  107. }
  108. }
  109. public char IndentChar {
  110. get { return indentChar; }
  111. set {
  112. indentChar = value;
  113. UpdateIndentChars ();
  114. }
  115. }
  116. public bool Namespaces {
  117. get { return namespaces; }
  118. set {
  119. if (ws != WriteState.Start)
  120. throw new InvalidOperationException ("NotInWriteState.");
  121. namespaces = value;
  122. }
  123. }
  124. public char QuoteChar {
  125. get { return quoteChar; }
  126. set {
  127. if ((value != '\'') && (value != '\"'))
  128. throw new ArgumentException ("This is an invalid XML attribute quote character. Valid attribute quote characters are ' and \".");
  129. quoteChar = value;
  130. }
  131. }
  132. public override WriteState WriteState {
  133. get { return ws; }
  134. }
  135. public override string XmlLang {
  136. get {
  137. string xmlLang = null;
  138. int i;
  139. for (i = openElementCount - 1; i >= 0; i--) {
  140. xmlLang = ((XmlTextWriterOpenElement) openElements [i]).XmlLang;
  141. if (xmlLang != null)
  142. break;
  143. }
  144. return xmlLang;
  145. }
  146. }
  147. public override XmlSpace XmlSpace {
  148. get {
  149. XmlSpace xmlSpace = XmlSpace.None;
  150. int i;
  151. for (i = openElementCount - 1; i >= 0; i--) {
  152. xmlSpace = ((XmlTextWriterOpenElement)openElements [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 (openElementCount > 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 [openElementCount - 1]).XmlLang = xmlLang;
  383. }
  384. if (openXmlSpace)
  385. {
  386. if (xmlSpace == XmlSpace.Preserve)
  387. w.Write ("preserve");
  388. else if (xmlSpace == XmlSpace.Default)
  389. w.Write ("default");
  390. openXmlSpace = false;
  391. ((XmlTextWriterOpenElement) openElements [openElementCount - 1]).XmlSpace = xmlSpace;
  392. }
  393. w.Write (quoteChar);
  394. openAttribute = false;
  395. if (saveAttributeValue) {
  396. if (savedAttributePrefix.Length > 0 && savingAttributeValue.Length == 0)
  397. throw new ArgumentException ("Cannot use prefix with an empty namespace.");
  398. // add namespace
  399. if (shouldAddSavedNsToManager) // not OLD one
  400. namespaceManager.AddNamespace (savedAttributePrefix, savingAttributeValue);
  401. userWrittenNamespaces [savedAttributePrefix] = savingAttributeValue;
  402. saveAttributeValue = false;
  403. savedAttributePrefix = String.Empty;
  404. savingAttributeValue = String.Empty;
  405. }
  406. }
  407. public override void WriteEndDocument ()
  408. {
  409. CloseOpenAttributeAndElements ();
  410. if (!hasRoot)
  411. throw new ArgumentException ("This document does not have a root element.");
  412. ws = WriteState.Start;
  413. hasRoot = false;
  414. }
  415. public override void WriteEndElement ()
  416. {
  417. WriteEndElementInternal (false);
  418. }
  419. private void WriteEndElementInternal (bool fullEndElement)
  420. {
  421. if (openElementCount == 0)
  422. throw new InvalidOperationException("There was no XML start tag open.");
  423. if (openAttribute)
  424. WriteEndAttribute ();
  425. indentLevel--;
  426. CheckState ();
  427. AddMissingElementXmlns ();
  428. if (openStartElement) {
  429. if (openAttribute)
  430. WriteEndAttribute ();
  431. if (fullEndElement) {
  432. w.Write ('>');
  433. w.Write (indentFormatting);
  434. w.Write ("</");
  435. XmlTextWriterOpenElement el = (XmlTextWriterOpenElement) openElements [openElementCount - 1];
  436. if (el.Prefix != String.Empty) {
  437. w.Write (el.Prefix);
  438. w.Write (':');
  439. }
  440. w.Write (el.LocalName);
  441. w.Write ('>');
  442. } else
  443. w.Write (" />");
  444. openElementCount--;
  445. openStartElement = false;
  446. } else {
  447. w.Write (indentFormatting);
  448. w.Write ("</");
  449. XmlTextWriterOpenElement el = (XmlTextWriterOpenElement) openElements [openElementCount - 1];
  450. openElementCount--;
  451. if (el.Prefix != String.Empty) {
  452. w.Write (el.Prefix);
  453. w.Write (':');
  454. }
  455. w.Write (el.LocalName);
  456. w.Write ('>');
  457. }
  458. namespaceManager.PopScope();
  459. }
  460. public override void WriteEntityRef (string name)
  461. {
  462. WriteRaw ("&");
  463. WriteStringInternal (name, true);
  464. WriteRaw (";");
  465. }
  466. public override void WriteFullEndElement ()
  467. {
  468. WriteEndElementInternal (true);
  469. }
  470. public override void WriteName (string name)
  471. {
  472. if (!XmlChar.IsName (name))
  473. throw new ArgumentException ("There is an invalid character: '" + name [0] +
  474. "'", "name");
  475. w.Write (name);
  476. }
  477. public override void WriteNmToken (string name)
  478. {
  479. if (!XmlChar.IsNmToken (name))
  480. throw new ArgumentException ("There is an invalid character: '" + name [0] +
  481. "'", "name");
  482. w.Write (name);
  483. }
  484. // LAMESPEC: It should reject such name that starts with "x" "m" "l" by XML specification, but
  485. // in fact it is used to write XmlDeclaration in WriteNode() (and it is inevitable since
  486. // WriteStartDocument() cannot specify encoding, while WriteNode() can write it).
  487. public override void WriteProcessingInstruction (string name, string text)
  488. {
  489. if ((name == null) || (name == string.Empty))
  490. throw new ArgumentException ();
  491. if (!XmlChar.IsName (name))
  492. throw new ArgumentException ("Invalid processing instruction name.");
  493. if ((text.IndexOf("?>") > 0))
  494. throw new ArgumentException ("Processing instruction cannot contain \"?>\" as its value.");
  495. CheckState ();
  496. CloseStartElement ();
  497. w.Write (indentFormatting);
  498. w.Write ("<?");
  499. w.Write (name);
  500. w.Write (' ');
  501. w.Write (text);
  502. w.Write ("?>");
  503. }
  504. public override void WriteQualifiedName (string localName, string ns)
  505. {
  506. if (localName == null || localName == String.Empty)
  507. throw new ArgumentException ();
  508. CheckState ();
  509. if (!openAttribute)
  510. CloseStartElement ();
  511. w.Write (namespaceManager.LookupPrefix (ns));
  512. w.Write (':');
  513. w.Write (localName);
  514. }
  515. public override void WriteRaw (string data)
  516. {
  517. WriteStringInternal (data, false);
  518. }
  519. public override void WriteRaw (char[] buffer, int index, int count)
  520. {
  521. // WriteRawInternal (new string (buffer, index, count));
  522. WriteStringInternal (new string (buffer, index, count), false);
  523. }
  524. public override void WriteStartAttribute (string prefix, string localName, string ns)
  525. {
  526. if (prefix == "xml") {
  527. // MS.NET looks to allow other names than
  528. // lang and space (e.g. xml:link, xml:hack).
  529. ns = XmlNamespaceManager.XmlnsXml;
  530. if (localName == "lang")
  531. openXmlLang = true;
  532. else if (localName == "space")
  533. openXmlSpace = true;
  534. }
  535. if (prefix == null)
  536. prefix = String.Empty;
  537. if (prefix.Length > 0 && (ns == null || ns.Length == 0))
  538. if (prefix != "xmlns")
  539. throw new ArgumentException ("Cannot use prefix with an empty namespace.");
  540. if ((prefix == "xmlns") && (localName.ToLower ().StartsWith ("xml")))
  541. 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);
  542. // Note that null namespace with "xmlns" are allowed.
  543. #if NET_1_0
  544. if ((prefix == "xmlns" || localName == "xmlns" && prefix == String.Empty) && ns != XmlnsNamespace)
  545. #else
  546. if ((prefix == "xmlns" || localName == "xmlns" && prefix == String.Empty) && ns != null && ns != XmlnsNamespace)
  547. #endif
  548. throw new ArgumentException (String.Format ("The 'xmlns' attribute is bound to the reserved namespace '{0}'", XmlnsNamespace));
  549. CheckState ();
  550. if (ws == WriteState.Content)
  551. throw new InvalidOperationException ("Token StartAttribute in state " + WriteState + " would result in an invalid XML document.");
  552. if (prefix == null)
  553. prefix = String.Empty;
  554. if (ns == null)
  555. ns = String.Empty;
  556. string formatPrefix = "";
  557. string formatSpace = "";
  558. if (ns != String.Empty && prefix != "xmlns") {
  559. string existingPrefix = namespaceManager.LookupPrefix (ns);
  560. if (existingPrefix == null || existingPrefix == "") {
  561. bool createPrefix = false;
  562. if (prefix == "")
  563. createPrefix = true;
  564. else {
  565. string existingNs = namespaceManager.LookupNamespace (prefix);
  566. if (existingNs != null) {
  567. namespaceManager.RemoveNamespace (prefix, existingNs);
  568. if (namespaceManager.LookupNamespace (prefix) != existingNs) {
  569. createPrefix = true;
  570. namespaceManager.AddNamespace (prefix, existingNs);
  571. }
  572. }
  573. }
  574. if (createPrefix)
  575. prefix = "d" + indentLevel + "p" + (newAttributeNamespaces.Count + 1);
  576. // check if prefix exists. If yes - check if namespace is the same.
  577. if (newAttributeNamespaces [prefix] == null)
  578. newAttributeNamespaces.Add (prefix, ns);
  579. else if (!newAttributeNamespaces [prefix].Equals (ns))
  580. throw new ArgumentException ("Duplicate prefix with different namespace");
  581. }
  582. if (prefix == String.Empty && ns != XmlnsNamespace)
  583. prefix = (existingPrefix == null) ?
  584. String.Empty : existingPrefix;
  585. }
  586. if (prefix != String.Empty)
  587. {
  588. formatPrefix = prefix + ":";
  589. }
  590. if (openStartElement || attributeWrittenForElement)
  591. formatSpace = " ";
  592. w.Write (formatSpace);
  593. w.Write (formatPrefix);
  594. w.Write (localName);
  595. w.Write ('=');
  596. w.Write (quoteChar);
  597. openAttribute = true;
  598. attributeWrittenForElement = true;
  599. ws = WriteState.Attribute;
  600. if (prefix == "xmlns" || prefix == String.Empty && localName == "xmlns") {
  601. if (prefix != openElementPrefix || openElementNS == null)
  602. shouldAddSavedNsToManager = true;
  603. saveAttributeValue = true;
  604. savedAttributePrefix = (prefix == "xmlns") ? localName : String.Empty;
  605. savingAttributeValue = String.Empty;
  606. }
  607. }
  608. public override void WriteStartDocument ()
  609. {
  610. WriteStartDocument ("");
  611. }
  612. public override void WriteStartDocument (bool standalone)
  613. {
  614. string standaloneFormatting;
  615. if (standalone == true)
  616. standaloneFormatting = String.Format (" standalone={0}yes{0}", quoteChar);
  617. else
  618. standaloneFormatting = String.Format (" standalone={0}no{0}", quoteChar);
  619. WriteStartDocument (standaloneFormatting);
  620. }
  621. private void WriteStartDocument (string standaloneFormatting)
  622. {
  623. if (documentStarted == true)
  624. throw new InvalidOperationException("WriteStartDocument should be the first call.");
  625. if (hasRoot)
  626. throw new XmlException ("WriteStartDocument called twice.");
  627. CheckState ();
  628. string encodingFormatting = "";
  629. if (!nullEncoding)
  630. encodingFormatting = String.Format (" encoding={0}{1}{0}", quoteChar, w.Encoding.WebName);
  631. w.Write("<?xml version={0}1.0{0}{1}{2}?>", quoteChar, encodingFormatting, standaloneFormatting);
  632. ws = WriteState.Prolog;
  633. }
  634. public override void WriteStartElement (string prefix, string localName, string ns)
  635. {
  636. if (!Namespaces && (((prefix != null) && (prefix != String.Empty))
  637. || ((ns != null) && (ns != String.Empty))))
  638. throw new ArgumentException ("Cannot set the namespace if Namespaces is 'false'.");
  639. if ((prefix != null && prefix != String.Empty) && ((ns == null) || (ns == String.Empty)))
  640. throw new ArgumentException ("Cannot use a prefix with an empty namespace.");
  641. // ignore non-namespaced node's prefix.
  642. if (ns == null || ns == String.Empty)
  643. prefix = String.Empty;
  644. WriteStartElementInternal (prefix, localName, ns);
  645. }
  646. private void WriteStartElementInternal (string prefix, string localName, string ns)
  647. {
  648. hasRoot = true;
  649. CheckState ();
  650. CloseStartElement ();
  651. newAttributeNamespaces.Clear ();
  652. userWrittenNamespaces.Clear ();
  653. shouldCheckElementXmlns = false;
  654. if (prefix == null && ns != null)
  655. prefix = namespaceManager.LookupPrefix (ns);
  656. if (prefix == null)
  657. prefix = String.Empty;
  658. w.Write (indentFormatting);
  659. w.Write ('<');
  660. if (prefix != String.Empty) {
  661. w.Write (prefix);
  662. w.Write (':');
  663. }
  664. w.Write (localName);
  665. if (openElements.Count == openElementCount)
  666. openElements.Add (new XmlTextWriterOpenElement (prefix, localName));
  667. else
  668. ((XmlTextWriterOpenElement) openElements [openElementCount]).Reset (prefix, localName);
  669. openElementCount++;
  670. ws = WriteState.Element;
  671. openStartElement = true;
  672. openElementNS = ns;
  673. openElementPrefix = prefix;
  674. namespaceManager.PushScope ();
  675. indentLevel++;
  676. if (ns != null) {
  677. if (ns.Length > 0) {
  678. string existing = LookupPrefix (ns);
  679. if (existing != prefix) {
  680. shouldCheckElementXmlns = true;
  681. namespaceManager.AddNamespace (prefix, ns);
  682. }
  683. } else {
  684. if (ns != namespaceManager.DefaultNamespace) {
  685. shouldCheckElementXmlns = true;
  686. namespaceManager.AddNamespace ("", ns);
  687. }
  688. }
  689. }
  690. }
  691. public override void WriteString (string text)
  692. {
  693. if (ws == WriteState.Prolog)
  694. throw new InvalidOperationException ("Token content in state Prolog would result in an invalid XML document.");
  695. WriteStringInternal (text, true);
  696. // MS.NET (1.0) saves attribute value only at WriteString.
  697. if (saveAttributeValue)
  698. // In most cases it will be called one time, so simply use string + string.
  699. savingAttributeValue += text;
  700. }
  701. string [] replacements = new string [] {
  702. "&amp;", "&lt;", "&gt;", "&quot;", "&apos;",
  703. "&#xD;", "&#xA;"};
  704. private string EscapeString (string source, bool skipQuotations)
  705. {
  706. int start = 0;
  707. int pos = 0;
  708. int count = source.Length;
  709. for (int i = 0; i < count; i++) {
  710. switch (source [i]) {
  711. case '&': pos = 0; break;
  712. case '<': pos = 1; break;
  713. case '>': pos = 2; break;
  714. case '\"':
  715. if (skipQuotations) continue;
  716. if (QuoteChar == '\'') continue;
  717. pos = 3; break;
  718. case '\'':
  719. if (skipQuotations) continue;
  720. if (QuoteChar == '\"') continue;
  721. pos = 4; break;
  722. case '\r':
  723. if (skipQuotations) continue;
  724. pos = 5; break;
  725. case '\n':
  726. if (skipQuotations) continue;
  727. pos = 6; break;
  728. default:
  729. continue;
  730. }
  731. if (cachedStringBuilder == null)
  732. cachedStringBuilder = new StringBuilder ();
  733. cachedStringBuilder.Append (source.Substring (start, i - start));
  734. cachedStringBuilder.Append (replacements [pos]);
  735. start = i + 1;
  736. }
  737. if (start == 0)
  738. return source;
  739. else if (start < count)
  740. cachedStringBuilder.Append (source.Substring (start, count - start));
  741. string s = cachedStringBuilder.ToString ();
  742. cachedStringBuilder.Length = 0;
  743. return s;
  744. }
  745. private void WriteStringInternal (string text, bool entitize)
  746. {
  747. if (text == null)
  748. text = String.Empty;
  749. if (text != String.Empty) {
  750. CheckState ();
  751. if (entitize)
  752. text = EscapeString (text, !openAttribute);
  753. if (!openAttribute)
  754. {
  755. IndentingOverriden = true;
  756. CloseStartElement ();
  757. }
  758. if (!openXmlLang && !openXmlSpace)
  759. w.Write (text);
  760. else
  761. {
  762. if (openXmlLang)
  763. xmlLang = text;
  764. else
  765. {
  766. switch (text)
  767. {
  768. case "default":
  769. xmlSpace = XmlSpace.Default;
  770. break;
  771. case "preserve":
  772. xmlSpace = XmlSpace.Preserve;
  773. break;
  774. default:
  775. throw new ArgumentException ("'{0}' is an invalid xml:space value.");
  776. }
  777. }
  778. }
  779. }
  780. }
  781. public override void WriteSurrogateCharEntity (char lowChar, char highChar)
  782. {
  783. if (lowChar < '\uDC00' || lowChar > '\uDFFF' ||
  784. highChar < '\uD800' || highChar > '\uDBFF')
  785. throw new ArgumentException ("Invalid (low, high) pair of characters was specified.");
  786. CheckState ();
  787. if (!openAttribute) {
  788. IndentingOverriden = true;
  789. CloseStartElement ();
  790. }
  791. w.Write ("&#x");
  792. w.Write (((int) ((highChar - 0xD800) * 0x400 + (lowChar - 0xDC00) + 0x10000)).ToString ("X"));
  793. w.Write (';');
  794. }
  795. public override void WriteWhitespace (string ws)
  796. {
  797. if (!XmlChar.IsWhitespace (ws))
  798. throw new ArgumentException ("Invalid Whitespace");
  799. CheckState ();
  800. if (!openAttribute) {
  801. IndentingOverriden = true;
  802. CloseStartElement ();
  803. }
  804. w.Write (ws);
  805. }
  806. #endregion
  807. }
  808. }