XmlTextWriter.cs 22 KB

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