XmlTextWriter.cs 23 KB

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