XmlTextWriter.cs 22 KB

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