XmlTextWriter.cs 21 KB

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