XmlTextWriter.cs 30 KB

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