XmlTextWriter.cs 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  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. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System;
  32. using System.Collections;
  33. using System.Globalization;
  34. using System.IO;
  35. using System.Text;
  36. namespace System.Xml
  37. {
  38. [MonoTODO ("NormalizeNewLines")]
  39. public class XmlTextWriter : XmlWriter
  40. {
  41. #region Fields
  42. const string XmlnsNamespace = "http://www.w3.org/2000/xmlns/";
  43. WriteState ws = WriteState.Start;
  44. TextWriter w;
  45. bool nullEncoding = false;
  46. bool openWriter = true;
  47. bool openStartElement = false;
  48. bool documentStarted = false;
  49. bool namespaces = true;
  50. bool openAttribute = false;
  51. bool attributeWrittenForElement = false;
  52. ArrayList openElements = new ArrayList ();
  53. int openElementCount;
  54. Formatting formatting = Formatting.None;
  55. int indentation = 2;
  56. char indentChar = ' ';
  57. string indentChars = " ";
  58. char quoteChar = '\"';
  59. int indentLevel = 0;
  60. bool indentLocal;
  61. Stream baseStream = null;
  62. string xmlLang = null;
  63. XmlSpace xmlSpace = XmlSpace.None;
  64. bool openXmlLang = false;
  65. bool openXmlSpace = false;
  66. string openElementPrefix;
  67. string openElementNS;
  68. bool hasRoot = false;
  69. bool isDocumentEntity = false;
  70. Hashtable newAttributeNamespaces = new Hashtable ();
  71. Hashtable userWrittenNamespaces = new Hashtable ();
  72. StringBuilder cachedStringBuilder;
  73. int autoCreatedPrefixes;
  74. XmlNamespaceManager namespaceManager = new XmlNamespaceManager (new NameTable ());
  75. string savingAttributeValue = String.Empty;
  76. bool saveAttributeValue;
  77. string savedAttributePrefix;
  78. bool shouldAddSavedNsToManager;
  79. bool shouldCheckElementXmlns;
  80. // XmlWriterSettings support
  81. bool checkCharacters;
  82. bool closeOutput = true;
  83. bool newLineOnAttributes;
  84. string newLineChars;
  85. #if NET_2_0
  86. bool outputXmlDeclaration;
  87. ConformanceLevel conformanceLevel;
  88. #endif
  89. #endregion
  90. #region Constructors
  91. public XmlTextWriter (TextWriter w) : base ()
  92. {
  93. this.w = w;
  94. nullEncoding = (w.Encoding == null);
  95. StreamWriter sw = w as StreamWriter;
  96. if (sw != null)
  97. baseStream = sw.BaseStream;
  98. newLineChars = w.NewLine;
  99. }
  100. public XmlTextWriter (Stream w, Encoding encoding) : base ()
  101. {
  102. if (encoding == null) {
  103. nullEncoding = true;
  104. this.w = new StreamWriter (w);
  105. } else
  106. this.w = new StreamWriter (w, encoding);
  107. baseStream = w;
  108. newLineChars = this.w.NewLine;
  109. }
  110. public XmlTextWriter (string filename, Encoding encoding) :
  111. this (new FileStream (filename, FileMode.Create, FileAccess.Write, FileShare.None), encoding)
  112. {
  113. }
  114. #endregion
  115. #region Properties
  116. public Stream BaseStream {
  117. get { return baseStream; }
  118. }
  119. public Formatting Formatting {
  120. get { return formatting; }
  121. set { formatting = value; }
  122. }
  123. private bool IndentingOverriden
  124. {
  125. get {
  126. if (openElementCount == 0)
  127. return false;
  128. else
  129. return ((XmlTextWriterOpenElement)
  130. openElements [openElementCount - 1]).IndentingOverriden;
  131. }
  132. set {
  133. if (openElementCount > 0)
  134. ((XmlTextWriterOpenElement) openElements [openElementCount - 1]).IndentingOverriden = value;
  135. }
  136. }
  137. private bool ParentIndentingOverriden {
  138. get {
  139. if (openElementCount < 2)
  140. return false;
  141. return ((XmlTextWriterOpenElement) openElements [openElementCount - 2]).IndentingOverriden;
  142. }
  143. }
  144. public int Indentation {
  145. get { return indentation; }
  146. set {
  147. indentation = value;
  148. UpdateIndentChars ();
  149. }
  150. }
  151. public char IndentChar {
  152. get { return indentChar; }
  153. set {
  154. indentChar = value;
  155. UpdateIndentChars ();
  156. }
  157. }
  158. #if NET_2_0
  159. internal bool CheckCharacters {
  160. get { return checkCharacters; }
  161. set { checkCharacters = value; }
  162. }
  163. internal bool CloseOutput {
  164. // get { return closeOutput; }
  165. set { closeOutput = value; }
  166. }
  167. // As for ConformanceLevel, MS.NET is inconsistent with
  168. // MSDN documentation. For example, even if ConformanceLevel
  169. // is set as .Auto, multiple WriteStartDocument() calls
  170. // result in an error.
  171. // ms-help://MS.NETFramework.v20.en/wd_xml/html/7db8802b-53d8-4735-a637-4d2d2158d643.htm
  172. [MonoTODO]
  173. internal ConformanceLevel ConformanceLevel {
  174. get { return conformanceLevel; }
  175. set {
  176. conformanceLevel = value;
  177. if (value == ConformanceLevel.Fragment)
  178. documentStarted = true;
  179. }
  180. }
  181. internal string IndentChars {
  182. // get { return indentChars; }
  183. set { indentChars = value == null ? String.Empty : value; }
  184. }
  185. internal string NewLineChars {
  186. // get { return newLineChars; }
  187. set { newLineChars = value == null ? String.Empty : value; }
  188. }
  189. internal bool NewLineOnAttributes {
  190. // get { return newLineOnAttributes; }
  191. set { newLineOnAttributes = value; }
  192. }
  193. internal bool OmitXmlDeclaration {
  194. // get { return !outputXmlDeclaration; }
  195. set { outputXmlDeclaration = !value; }
  196. }
  197. #endif
  198. public bool Namespaces {
  199. get { return namespaces; }
  200. set {
  201. if (ws != WriteState.Start)
  202. throw new InvalidOperationException ("NotInWriteState.");
  203. namespaces = value;
  204. }
  205. }
  206. public char QuoteChar {
  207. get { return quoteChar; }
  208. set {
  209. if ((value != '\'') && (value != '\"'))
  210. throw new ArgumentException ("This is an invalid XML attribute quote character. Valid attribute quote characters are ' and \".");
  211. quoteChar = value;
  212. }
  213. }
  214. public override WriteState WriteState {
  215. get { return ws; }
  216. }
  217. public override string XmlLang {
  218. get {
  219. string xmlLang = null;
  220. int i;
  221. for (i = openElementCount - 1; i >= 0; i--) {
  222. xmlLang = ((XmlTextWriterOpenElement) openElements [i]).XmlLang;
  223. if (xmlLang != null)
  224. break;
  225. }
  226. return xmlLang;
  227. }
  228. }
  229. public override XmlSpace XmlSpace {
  230. get {
  231. XmlSpace xmlSpace = XmlSpace.None;
  232. int i;
  233. for (i = openElementCount - 1; i >= 0; i--) {
  234. xmlSpace = ((XmlTextWriterOpenElement)openElements [i]).XmlSpace;
  235. if (xmlSpace != XmlSpace.None)
  236. break;
  237. }
  238. return xmlSpace;
  239. }
  240. }
  241. #endregion
  242. #region Methods
  243. #if NET_2_0
  244. private void CheckStartDocument ()
  245. {
  246. if (outputXmlDeclaration &&
  247. conformanceLevel == ConformanceLevel.Document &&
  248. ws == WriteState.Start)
  249. WriteStartDocument ();
  250. }
  251. #endif
  252. private void AddMissingElementXmlns ()
  253. {
  254. // output namespace declaration if not exist.
  255. string prefix = openElementPrefix;
  256. string ns = openElementNS;
  257. openElementPrefix = null;
  258. openElementNS = null;
  259. // LAMESPEC: If prefix was already assigned another nsuri, then this element's nsuri goes away!
  260. if (this.shouldCheckElementXmlns) {
  261. if (userWrittenNamespaces [prefix] == null) {
  262. if (prefix != string.Empty) {
  263. w.Write (" xmlns:");
  264. w.Write (prefix);
  265. w.Write ('=');
  266. w.Write (quoteChar);
  267. w.Write (EscapeString (ns, false));
  268. w.Write (quoteChar);
  269. }
  270. else {
  271. w.Write (" xmlns=");
  272. w.Write (quoteChar);
  273. w.Write (EscapeString (ns, false));
  274. w.Write (quoteChar);
  275. }
  276. }
  277. shouldCheckElementXmlns = false;
  278. }
  279. if (newAttributeNamespaces.Count > 0)
  280. {
  281. foreach (DictionaryEntry ent in newAttributeNamespaces)
  282. {
  283. string ans = (string) ent.Value;
  284. string aprefix = (string) ent.Key;
  285. if (namespaceManager.LookupNamespace (aprefix, false) == ans)
  286. continue;
  287. ans = EscapeString (ans, false);
  288. w.Write (" xmlns:");
  289. w.Write (aprefix);
  290. w.Write ('=');
  291. w.Write (quoteChar);
  292. w.Write (ans);
  293. w.Write (quoteChar);
  294. namespaceManager.AddNamespace (aprefix, ans);
  295. }
  296. newAttributeNamespaces.Clear ();
  297. }
  298. autoCreatedPrefixes = 0;
  299. }
  300. private void CheckState ()
  301. {
  302. #if NET_2_0
  303. CheckStartDocument ();
  304. #endif
  305. CheckOutputState ();
  306. }
  307. private void CheckOutputState ()
  308. {
  309. if (!openWriter) {
  310. throw new InvalidOperationException ("The Writer is closed.");
  311. }
  312. if ((documentStarted == true) && (formatting == Formatting.Indented) && (!IndentingOverriden)) {
  313. indentLocal = true;
  314. }
  315. else
  316. indentLocal = false;
  317. documentStarted = true;
  318. }
  319. public override void Close ()
  320. {
  321. CloseOpenAttributeAndElements ();
  322. if (closeOutput)
  323. w.Close ();
  324. else if (ws != WriteState.Closed)
  325. w.Flush ();
  326. ws = WriteState.Closed;
  327. openWriter = false;
  328. }
  329. private void CloseOpenAttributeAndElements ()
  330. {
  331. if (openAttribute)
  332. WriteEndAttribute ();
  333. while (openElementCount > 0) {
  334. WriteEndElement();
  335. }
  336. }
  337. private void CloseStartElement ()
  338. {
  339. if (!openStartElement)
  340. return;
  341. AddMissingElementXmlns ();
  342. w.Write (">");
  343. ws = WriteState.Content;
  344. openStartElement = false;
  345. attributeWrittenForElement = false;
  346. newAttributeNamespaces.Clear ();
  347. userWrittenNamespaces.Clear ();
  348. }
  349. public override void Flush ()
  350. {
  351. w.Flush ();
  352. }
  353. public override string LookupPrefix (string ns)
  354. {
  355. if (ns == null || ns == String.Empty)
  356. throw new ArgumentException ("The Namespace cannot be empty.");
  357. string prefix = namespaceManager.LookupPrefix (ns, false);
  358. // XmlNamespaceManager might return such prefix that
  359. // is *previously* mapped to ns passed above.
  360. if (prefix == null || namespaceManager.LookupNamespace (prefix) != ns)
  361. return null;
  362. // XmlNamespaceManager has changed to return null when NSURI not found.
  363. // (Contradiction to the ECMA documentation.)
  364. return prefix;
  365. }
  366. private void UpdateIndentChars ()
  367. {
  368. indentChars = new string (indentChar, indentation);
  369. }
  370. public override void WriteBase64 (byte[] buffer, int index, int count)
  371. {
  372. CheckState ();
  373. if (!openAttribute) {
  374. IndentingOverriden = true;
  375. CloseStartElement ();
  376. }
  377. w.Write (Convert.ToBase64String (buffer, index, count));
  378. }
  379. public override void WriteBinHex (byte[] buffer, int index, int count)
  380. {
  381. CheckState ();
  382. if (!openAttribute) {
  383. IndentingOverriden = true;
  384. CloseStartElement ();
  385. }
  386. XmlConvert.WriteBinHex (buffer, index, count, w);
  387. }
  388. public override void WriteCData (string text)
  389. {
  390. if (text.IndexOf ("]]>") >= 0)
  391. throw new ArgumentException ("CDATA section cannot contain text \"]]>\".");
  392. CheckState ();
  393. IndentingOverriden = true;
  394. CloseStartElement ();
  395. w.Write ("<![CDATA[");
  396. w.Write (text);
  397. w.Write ("]]>");
  398. }
  399. public override void WriteCharEntity (char ch)
  400. {
  401. Int16 intCh = (Int16)ch;
  402. // Make sure the character is not in the surrogate pair
  403. // character range, 0xd800- 0xdfff
  404. if ((intCh >= -10240) && (intCh <= -8193))
  405. throw new ArgumentException ("Surrogate Pair is invalid.");
  406. w.Write("&#x{0:X};", intCh);
  407. }
  408. public override void WriteChars (char[] buffer, int index, int count)
  409. {
  410. CheckState ();
  411. if (!openAttribute) {
  412. IndentingOverriden = true;
  413. CloseStartElement ();
  414. }
  415. w.Write (buffer, index, count);
  416. }
  417. public override void WriteComment (string text)
  418. {
  419. if (text.EndsWith("-"))
  420. throw new ArgumentException ("An XML comment cannot contain \"--\" inside.");
  421. else if (text.IndexOf("--") > 0)
  422. throw new ArgumentException ("An XML comment cannot end with \"-\".");
  423. CheckState ();
  424. CloseStartElement ();
  425. WriteIndent ();
  426. w.Write ("<!--");
  427. w.Write (text);
  428. w.Write ("-->");
  429. }
  430. public override void WriteDocType (string name, string pubid, string sysid, string subset)
  431. {
  432. if (name == null || name.Trim (XmlChar.WhitespaceChars).Length == 0)
  433. throw new ArgumentException ("Invalid DOCTYPE name", "name");
  434. if (ws == WriteState.Prolog && formatting == Formatting.Indented)
  435. w.WriteLine ();
  436. w.Write ("<!DOCTYPE ");
  437. w.Write (name);
  438. if (pubid != null) {
  439. w.Write (" PUBLIC ");
  440. w.Write (quoteChar);
  441. w.Write (pubid);
  442. w.Write (quoteChar);
  443. w.Write (' ');
  444. w.Write (quoteChar);
  445. w.Write (sysid);
  446. w.Write (quoteChar);
  447. } else if (sysid != null) {
  448. w.Write (" SYSTEM ");
  449. w.Write (quoteChar);
  450. w.Write (sysid);
  451. w.Write (quoteChar);
  452. }
  453. if (subset != null) {
  454. w.Write ('[');
  455. w.Write (subset);
  456. w.Write (']');
  457. }
  458. w.Write('>');
  459. }
  460. public override void WriteEndAttribute ()
  461. {
  462. if (!openAttribute)
  463. throw new InvalidOperationException("Token EndAttribute in state Start would result in an invalid XML document.");
  464. CheckState ();
  465. if (openXmlLang) {
  466. w.Write (xmlLang);
  467. openXmlLang = false;
  468. ((XmlTextWriterOpenElement) openElements [openElementCount - 1]).XmlLang = xmlLang;
  469. }
  470. if (openXmlSpace)
  471. {
  472. if (xmlSpace == XmlSpace.Preserve)
  473. w.Write ("preserve");
  474. else if (xmlSpace == XmlSpace.Default)
  475. w.Write ("default");
  476. openXmlSpace = false;
  477. ((XmlTextWriterOpenElement) openElements [openElementCount - 1]).XmlSpace = xmlSpace;
  478. }
  479. w.Write (quoteChar);
  480. openAttribute = false;
  481. if (saveAttributeValue) {
  482. if (savedAttributePrefix.Length > 0 && savingAttributeValue.Length == 0)
  483. throw new ArgumentException ("Cannot use prefix with an empty namespace.");
  484. // add namespace
  485. if (shouldAddSavedNsToManager) // not OLD one
  486. namespaceManager.AddNamespace (savedAttributePrefix, savingAttributeValue);
  487. userWrittenNamespaces [savedAttributePrefix] = savingAttributeValue;
  488. saveAttributeValue = false;
  489. savedAttributePrefix = String.Empty;
  490. savingAttributeValue = String.Empty;
  491. }
  492. }
  493. public override void WriteEndDocument ()
  494. {
  495. CloseOpenAttributeAndElements ();
  496. if (!hasRoot)
  497. throw new ArgumentException ("This document does not have a root element.");
  498. ws = WriteState.Start;
  499. hasRoot = false;
  500. }
  501. public override void WriteEndElement ()
  502. {
  503. WriteEndElementInternal (false);
  504. }
  505. private void WriteIndent ()
  506. {
  507. if (!indentLocal)
  508. return;
  509. w.Write (newLineChars);
  510. for (int i = 0; i < indentLevel; i++)
  511. w.Write (indentChars);
  512. }
  513. private void WriteEndElementInternal (bool fullEndElement)
  514. {
  515. if (openElementCount == 0)
  516. throw new InvalidOperationException("There was no XML start tag open.");
  517. if (openAttribute)
  518. WriteEndAttribute ();
  519. indentLevel--;
  520. CheckState ();
  521. AddMissingElementXmlns ();
  522. if (openStartElement) {
  523. if (openAttribute)
  524. WriteEndAttribute ();
  525. if (fullEndElement) {
  526. w.Write ('>');
  527. if (!ParentIndentingOverriden)
  528. WriteIndent ();
  529. w.Write ("</");
  530. XmlTextWriterOpenElement el = (XmlTextWriterOpenElement) openElements [openElementCount - 1];
  531. if (el.Prefix != String.Empty) {
  532. w.Write (el.Prefix);
  533. w.Write (':');
  534. }
  535. w.Write (el.LocalName);
  536. w.Write ('>');
  537. } else
  538. w.Write (" />");
  539. openElementCount--;
  540. openStartElement = false;
  541. } else {
  542. WriteIndent ();
  543. w.Write ("</");
  544. XmlTextWriterOpenElement el = (XmlTextWriterOpenElement) openElements [openElementCount - 1];
  545. openElementCount--;
  546. if (el.Prefix != String.Empty) {
  547. w.Write (el.Prefix);
  548. w.Write (':');
  549. }
  550. w.Write (el.LocalName);
  551. w.Write ('>');
  552. }
  553. namespaceManager.PopScope();
  554. }
  555. public override void WriteEntityRef (string name)
  556. {
  557. WriteRaw ("&");
  558. WriteStringInternal (name, true);
  559. WriteRaw (";");
  560. }
  561. public override void WriteFullEndElement ()
  562. {
  563. WriteEndElementInternal (true);
  564. }
  565. public override void WriteName (string name)
  566. {
  567. WriteNameInternal (name);
  568. }
  569. public override void WriteNmToken (string name)
  570. {
  571. WriteNmTokenInternal (name);
  572. }
  573. // LAMESPEC: It should reject such name that starts with "x" "m" "l" by XML specification, but
  574. // in fact it is used to write XmlDeclaration in WriteNode() (and it is inevitable since
  575. // WriteStartDocument() cannot specify encoding, while WriteNode() can write it).
  576. public override void WriteProcessingInstruction (string name, string text)
  577. {
  578. if ((name == null) || (name == string.Empty))
  579. throw new ArgumentException ("Argument processing instruction name must not be null or empty.");
  580. if (!XmlChar.IsName (name))
  581. throw new ArgumentException ("Invalid processing instruction name.");
  582. if ((text.IndexOf("?>") > 0))
  583. throw new ArgumentException ("Processing instruction cannot contain \"?>\" as its value.");
  584. CheckState ();
  585. CloseStartElement ();
  586. WriteIndent ();
  587. w.Write ("<?");
  588. w.Write (name);
  589. w.Write (' ');
  590. w.Write (text);
  591. w.Write ("?>");
  592. }
  593. public override void WriteQualifiedName (string localName, string ns)
  594. {
  595. if (!XmlChar.IsNCName (localName))
  596. throw new ArgumentException (String.Format ("Invalid local name '{0}'", localName));
  597. CheckState ();
  598. if (!openAttribute)
  599. CloseStartElement ();
  600. // WriteQualifiedName internal will reject such
  601. // qname whose namespace is not declared.
  602. string prefix = null;
  603. if (openAttribute && ns != String.Empty && LookupPrefix (ns) == null) {
  604. prefix = CheckNewPrefix (true, null, ns);
  605. namespaceManager.AddNamespace (prefix, ns);
  606. }
  607. WriteQualifiedNameInternal (localName, ns);
  608. if (prefix != null) {
  609. namespaceManager.RemoveNamespace (prefix, ns);
  610. newAttributeNamespaces [prefix] = ns;
  611. }
  612. }
  613. public override void WriteRaw (string data)
  614. {
  615. if (ws == WriteState.Start)
  616. ws = WriteState.Prolog;
  617. WriteStringInternal (data, false);
  618. }
  619. public override void WriteRaw (char[] buffer, int index, int count)
  620. {
  621. WriteRaw (new string (buffer, index, count));
  622. }
  623. public override void WriteStartAttribute (string prefix, string localName, string ns)
  624. {
  625. if (prefix == "xml") {
  626. // MS.NET looks to allow other names than
  627. // lang and space (e.g. xml:link, xml:hack).
  628. ns = XmlNamespaceManager.XmlnsXml;
  629. if (localName == "lang")
  630. openXmlLang = true;
  631. else if (localName == "space")
  632. openXmlSpace = true;
  633. }
  634. if (prefix == null)
  635. prefix = String.Empty;
  636. if (prefix.Length > 0 && (ns == null || ns.Length == 0))
  637. if (prefix != "xmlns")
  638. throw new ArgumentException ("Cannot use prefix with an empty namespace.");
  639. if (prefix == "xmlns") {
  640. if (localName == null || localName.Length == 0) {
  641. localName = prefix;
  642. prefix = String.Empty;
  643. }
  644. }
  645. // Note that null namespace with "xmlns" are allowed.
  646. #if NET_1_0
  647. if ((prefix == "xmlns" || localName == "xmlns" && prefix == String.Empty) && ns != XmlnsNamespace)
  648. #else
  649. if ((prefix == "xmlns" || localName == "xmlns" && prefix == String.Empty) && ns != null && ns != XmlnsNamespace)
  650. #endif
  651. throw new ArgumentException (String.Format ("The 'xmlns' attribute is bound to the reserved namespace '{0}'", XmlnsNamespace));
  652. CheckState ();
  653. if (ws == WriteState.Content)
  654. throw new InvalidOperationException ("Token StartAttribute in state " + WriteState + " would result in an invalid XML document.");
  655. if (prefix == null)
  656. prefix = String.Empty;
  657. if (ns == null)
  658. ns = String.Empty;
  659. string formatPrefix = "";
  660. if (ns != String.Empty && prefix != "xmlns") {
  661. string existingPrefix = namespaceManager.LookupPrefix (ns, false);
  662. if (existingPrefix == null || existingPrefix == "") {
  663. bool createPrefix = false;
  664. if (prefix == "")
  665. createPrefix = true;
  666. else {
  667. string existingNs = namespaceManager.LookupNamespace (prefix, false);
  668. if (existingNs != null) {
  669. namespaceManager.RemoveNamespace (prefix, existingNs);
  670. if (namespaceManager.LookupNamespace (prefix, false) != existingNs) {
  671. createPrefix = true;
  672. namespaceManager.AddNamespace (prefix, existingNs);
  673. }
  674. }
  675. }
  676. prefix = CheckNewPrefix (createPrefix, prefix, ns);
  677. }
  678. if (prefix == String.Empty && ns != XmlnsNamespace)
  679. prefix = (existingPrefix == null) ?
  680. String.Empty : existingPrefix;
  681. }
  682. if (prefix != String.Empty)
  683. {
  684. formatPrefix = prefix + ":";
  685. }
  686. if (openStartElement || attributeWrittenForElement) {
  687. if (newLineOnAttributes)
  688. WriteIndent ();
  689. else
  690. w.Write (" ");
  691. }
  692. w.Write (formatPrefix);
  693. w.Write (localName);
  694. w.Write ('=');
  695. w.Write (quoteChar);
  696. openAttribute = true;
  697. attributeWrittenForElement = true;
  698. ws = WriteState.Attribute;
  699. if (prefix == "xmlns" || prefix == String.Empty && localName == "xmlns") {
  700. if (prefix != openElementPrefix || openElementNS == null)
  701. shouldAddSavedNsToManager = true;
  702. saveAttributeValue = true;
  703. savedAttributePrefix = (prefix == "xmlns") ? localName : String.Empty;
  704. savingAttributeValue = String.Empty;
  705. }
  706. }
  707. private string CheckNewPrefix (bool createPrefix, string prefix, string ns)
  708. {
  709. do {
  710. if (createPrefix)
  711. prefix = "d" + indentLevel + "p" + (++autoCreatedPrefixes);
  712. createPrefix = false;
  713. // Check if prefix exists.
  714. // If yes - check if namespace is the same.
  715. if (newAttributeNamespaces [prefix] == null)
  716. newAttributeNamespaces.Add (prefix, ns);
  717. else if (!newAttributeNamespaces [prefix].Equals (ns))
  718. createPrefix = true;
  719. } while (createPrefix);
  720. return prefix;
  721. }
  722. public override void WriteStartDocument ()
  723. {
  724. WriteStartDocument ("");
  725. }
  726. public override void WriteStartDocument (bool standalone)
  727. {
  728. string standaloneFormatting;
  729. if (standalone == true)
  730. standaloneFormatting = String.Format (" standalone={0}yes{0}", quoteChar);
  731. else
  732. standaloneFormatting = String.Format (" standalone={0}no{0}", quoteChar);
  733. WriteStartDocument (standaloneFormatting);
  734. }
  735. private void WriteStartDocument (string standaloneFormatting)
  736. {
  737. if (documentStarted == true)
  738. throw new InvalidOperationException("WriteStartDocument should be the first call.");
  739. if (hasRoot)
  740. throw new XmlException ("WriteStartDocument called twice.");
  741. isDocumentEntity = true;
  742. // CheckState ();
  743. CheckOutputState ();
  744. string encodingFormatting = "";
  745. if (!nullEncoding)
  746. encodingFormatting = String.Format (" encoding={0}{1}{0}", quoteChar, w.Encoding.WebName);
  747. w.Write("<?xml version={0}1.0{0}{1}{2}?>", quoteChar, encodingFormatting, standaloneFormatting);
  748. ws = WriteState.Prolog;
  749. }
  750. public override void WriteStartElement (string prefix, string localName, string ns)
  751. {
  752. if (!Namespaces && (((prefix != null) && (prefix != String.Empty))
  753. || ((ns != null) && (ns != String.Empty))))
  754. throw new ArgumentException ("Cannot set the namespace if Namespaces is 'false'.");
  755. if ((prefix != null && prefix != String.Empty) && ((ns == null) || (ns == String.Empty)))
  756. throw new ArgumentException ("Cannot use a prefix with an empty namespace.");
  757. // ignore non-namespaced node's prefix.
  758. if (ns == null || ns == String.Empty)
  759. prefix = String.Empty;
  760. WriteStartElementInternal (prefix, localName, ns);
  761. }
  762. private void WriteStartElementInternal (string prefix, string localName, string ns)
  763. {
  764. CheckState ();
  765. hasRoot = true;
  766. CloseStartElement ();
  767. newAttributeNamespaces.Clear ();
  768. userWrittenNamespaces.Clear ();
  769. shouldCheckElementXmlns = false;
  770. if (prefix == null && ns != null)
  771. prefix = namespaceManager.LookupPrefix (ns, false);
  772. if (prefix == null)
  773. prefix = String.Empty;
  774. WriteIndent ();
  775. w.Write ('<');
  776. if (prefix != String.Empty) {
  777. w.Write (prefix);
  778. w.Write (':');
  779. }
  780. w.Write (localName);
  781. if (openElements.Count == openElementCount)
  782. openElements.Add (new XmlTextWriterOpenElement (prefix, localName));
  783. else
  784. ((XmlTextWriterOpenElement) openElements [openElementCount]).Reset (prefix, localName);
  785. openElementCount++;
  786. ws = WriteState.Element;
  787. openStartElement = true;
  788. openElementNS = ns;
  789. openElementPrefix = prefix;
  790. namespaceManager.PushScope ();
  791. indentLevel++;
  792. if (ns != null) {
  793. if (ns.Length > 0) {
  794. string existing = LookupPrefix (ns);
  795. if (existing != prefix) {
  796. shouldCheckElementXmlns = true;
  797. namespaceManager.AddNamespace (prefix, ns);
  798. }
  799. } else {
  800. if (ns != namespaceManager.DefaultNamespace) {
  801. shouldCheckElementXmlns = true;
  802. namespaceManager.AddNamespace ("", ns);
  803. }
  804. }
  805. }
  806. }
  807. public override void WriteString (string text)
  808. {
  809. switch (ws) {
  810. case WriteState.Start:
  811. case WriteState.Prolog:
  812. if (isDocumentEntity)
  813. throw new InvalidOperationException ("Token content in state Prolog would result in an invalid XML document.");
  814. ws = WriteState.Content;
  815. break;
  816. }
  817. WriteStringInternal (text, true);
  818. // MS.NET (1.0) saves attribute value only at WriteString.
  819. if (saveAttributeValue)
  820. // In most cases it will be called one time, so simply use string + string.
  821. savingAttributeValue += text;
  822. }
  823. string [] replacements = new string [] {
  824. "&amp;", "&lt;", "&gt;", "&quot;", "&apos;",
  825. "&#xD;", "&#xA;"};
  826. private string EscapeString (string source, bool skipQuotations)
  827. {
  828. int start = 0;
  829. int pos = 0;
  830. int count = source.Length;
  831. char invalid = ' ';
  832. for (int i = 0; i < count; i++) {
  833. switch (source [i]) {
  834. case '&': pos = 0; break;
  835. case '<': pos = 1; break;
  836. case '>': pos = 2; break;
  837. case '\"':
  838. if (skipQuotations) continue;
  839. if (QuoteChar == '\'') continue;
  840. pos = 3; break;
  841. case '\'':
  842. if (skipQuotations) continue;
  843. if (QuoteChar == '\"') continue;
  844. pos = 4; break;
  845. case '\r':
  846. if (skipQuotations) continue;
  847. pos = 5; break;
  848. case '\n':
  849. if (skipQuotations) continue;
  850. pos = 6; break;
  851. default:
  852. if (XmlChar.IsInvalid (source [i])) {
  853. if (checkCharacters)
  854. throw new ArgumentException (String.Format ("Character hexadecimal value {0:4x} is invalid.", (int) source [i]));
  855. invalid = source [i];
  856. pos = -1;
  857. break;
  858. }
  859. else
  860. continue;
  861. }
  862. if (cachedStringBuilder == null)
  863. cachedStringBuilder = new StringBuilder ();
  864. cachedStringBuilder.Append (source.Substring (start, i - start));
  865. if (pos < 0) {
  866. cachedStringBuilder.Append ("&#x");
  867. // if (invalid < (char) 255)
  868. // cachedStringBuilder.Append (((int) invalid).ToString ("X02", CultureInfo.InvariantCulture));
  869. // else
  870. // cachedStringBuilder.Append (((int) invalid).ToString ("X04", CultureInfo.InvariantCulture));
  871. cachedStringBuilder.Append (((int) invalid).ToString ("X", CultureInfo.InvariantCulture));
  872. cachedStringBuilder.Append (";");
  873. }
  874. else
  875. cachedStringBuilder.Append (replacements [pos]);
  876. start = i + 1;
  877. }
  878. if (start == 0)
  879. return source;
  880. else if (start < count)
  881. cachedStringBuilder.Append (source.Substring (start, count - start));
  882. string s = cachedStringBuilder.ToString ();
  883. cachedStringBuilder.Length = 0;
  884. return s;
  885. }
  886. private void WriteStringInternal (string text, bool entitize)
  887. {
  888. if (text == null)
  889. text = String.Empty;
  890. if (text != String.Empty) {
  891. CheckState ();
  892. if (entitize)
  893. text = EscapeString (text, !openAttribute);
  894. if (!openAttribute)
  895. {
  896. IndentingOverriden = true;
  897. CloseStartElement ();
  898. }
  899. if (!openXmlLang && !openXmlSpace)
  900. w.Write (text);
  901. else
  902. {
  903. if (openXmlLang)
  904. xmlLang = text;
  905. else
  906. {
  907. switch (text)
  908. {
  909. case "default":
  910. xmlSpace = XmlSpace.Default;
  911. break;
  912. case "preserve":
  913. xmlSpace = XmlSpace.Preserve;
  914. break;
  915. default:
  916. throw new ArgumentException ("'{0}' is an invalid xml:space value.");
  917. }
  918. }
  919. }
  920. }
  921. }
  922. public override void WriteSurrogateCharEntity (char lowChar, char highChar)
  923. {
  924. if (lowChar < '\uDC00' || lowChar > '\uDFFF' ||
  925. highChar < '\uD800' || highChar > '\uDBFF')
  926. throw new ArgumentException ("Invalid (low, high) pair of characters was specified.");
  927. CheckState ();
  928. if (!openAttribute) {
  929. IndentingOverriden = true;
  930. CloseStartElement ();
  931. }
  932. w.Write ("&#x");
  933. w.Write (((int) ((highChar - 0xD800) * 0x400 + (lowChar - 0xDC00) + 0x10000)).ToString ("X", CultureInfo.InvariantCulture));
  934. w.Write (';');
  935. }
  936. public override void WriteWhitespace (string ws)
  937. {
  938. if (!XmlChar.IsWhitespace (ws))
  939. throw new ArgumentException ("Invalid Whitespace");
  940. CheckState ();
  941. if (!openAttribute) {
  942. IndentingOverriden = true;
  943. CloseStartElement ();
  944. }
  945. w.Write (ws);
  946. }
  947. #endregion
  948. }
  949. }