XmlTextWriter.cs 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  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 new ArgumentException ("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 (!openWriter) {
  314. throw new InvalidOperationException ("The Writer is closed.");
  315. }
  316. if ((documentStarted == true) && (formatting == Formatting.Indented) && (!IndentingOverriden)) {
  317. indentLocal = true;
  318. }
  319. else
  320. indentLocal = false;
  321. documentStarted = true;
  322. }
  323. public override void Close ()
  324. {
  325. CloseOpenAttributeAndElements ();
  326. if (closeOutput)
  327. w.Close ();
  328. else if (ws != WriteState.Closed)
  329. w.Flush ();
  330. ws = WriteState.Closed;
  331. openWriter = false;
  332. }
  333. private void CloseOpenAttributeAndElements ()
  334. {
  335. if (openAttribute)
  336. WriteEndAttribute ();
  337. while (openElementCount > 0) {
  338. WriteEndElement();
  339. }
  340. }
  341. private void CloseStartElement ()
  342. {
  343. if (!openStartElement)
  344. return;
  345. AddMissingElementXmlns ();
  346. w.Write (">");
  347. ws = WriteState.Content;
  348. openStartElement = false;
  349. attributeWrittenForElement = false;
  350. newAttributeNamespaces.Clear ();
  351. userWrittenNamespaces.Clear ();
  352. }
  353. public override void Flush ()
  354. {
  355. w.Flush ();
  356. }
  357. public override string LookupPrefix (string ns)
  358. {
  359. if (ns == null || ns == String.Empty)
  360. throw new ArgumentException ("The Namespace cannot be empty.");
  361. string prefix = namespaceManager.LookupPrefix (ns, false);
  362. // XmlNamespaceManager might return such prefix that
  363. // is *previously* mapped to ns passed above.
  364. if (prefix == null || namespaceManager.LookupNamespace (prefix) != ns)
  365. return null;
  366. // XmlNamespaceManager has changed to return null when NSURI not found.
  367. // (Contradiction to the ECMA documentation.)
  368. return prefix;
  369. }
  370. private void UpdateIndentChars ()
  371. {
  372. indentChars = new string (indentChar, indentation);
  373. }
  374. public override void WriteBase64 (byte[] buffer, int index, int count)
  375. {
  376. CheckState ();
  377. if (!openAttribute) {
  378. IndentingOverriden = true;
  379. CloseStartElement ();
  380. }
  381. w.Write (Convert.ToBase64String (buffer, index, count));
  382. }
  383. public override void WriteBinHex (byte[] buffer, int index, int count)
  384. {
  385. CheckState ();
  386. if (!openAttribute) {
  387. IndentingOverriden = true;
  388. CloseStartElement ();
  389. }
  390. XmlConvert.WriteBinHex (buffer, index, count, w);
  391. }
  392. public override void WriteCData (string text)
  393. {
  394. if (text.IndexOf ("]]>") >= 0)
  395. throw new ArgumentException ("CDATA section cannot contain text \"]]>\".");
  396. CheckState ();
  397. IndentingOverriden = true;
  398. CloseStartElement ();
  399. w.Write ("<![CDATA[");
  400. w.Write (text);
  401. w.Write ("]]>");
  402. }
  403. public override void WriteCharEntity (char ch)
  404. {
  405. Int16 intCh = (Int16)ch;
  406. // Make sure the character is not in the surrogate pair
  407. // character range, 0xd800- 0xdfff
  408. if ((intCh >= -10240) && (intCh <= -8193))
  409. throw new ArgumentException ("Surrogate Pair is invalid.");
  410. w.Write("&#x{0:X};", intCh);
  411. }
  412. public override void WriteChars (char[] buffer, int index, int count)
  413. {
  414. CheckState ();
  415. if (!openAttribute) {
  416. IndentingOverriden = true;
  417. CloseStartElement ();
  418. }
  419. w.Write (buffer, index, count);
  420. }
  421. public override void WriteComment (string text)
  422. {
  423. if (text.EndsWith("-"))
  424. throw new ArgumentException ("An XML comment cannot contain \"--\" inside.");
  425. else if (text.IndexOf("--") > 0)
  426. throw new ArgumentException ("An XML comment cannot end with \"-\".");
  427. CheckState ();
  428. CloseStartElement ();
  429. WriteIndent ();
  430. w.Write ("<!--");
  431. w.Write (text);
  432. w.Write ("-->");
  433. }
  434. public override void WriteDocType (string name, string pubid, string sysid, string subset)
  435. {
  436. if (name == null || name.Trim (XmlChar.WhitespaceChars).Length == 0)
  437. throw new ArgumentException ("Invalid DOCTYPE name", "name");
  438. if (ws == WriteState.Prolog && formatting == Formatting.Indented)
  439. w.WriteLine ();
  440. w.Write ("<!DOCTYPE ");
  441. w.Write (name);
  442. if (pubid != null) {
  443. w.Write (" PUBLIC ");
  444. w.Write (quoteChar);
  445. w.Write (pubid);
  446. w.Write (quoteChar);
  447. w.Write (' ');
  448. w.Write (quoteChar);
  449. w.Write (sysid);
  450. w.Write (quoteChar);
  451. } else if (sysid != null) {
  452. w.Write (" SYSTEM ");
  453. w.Write (quoteChar);
  454. w.Write (sysid);
  455. w.Write (quoteChar);
  456. }
  457. if (subset != null) {
  458. w.Write ('[');
  459. w.Write (subset);
  460. w.Write (']');
  461. }
  462. w.Write('>');
  463. }
  464. public override void WriteEndAttribute ()
  465. {
  466. if (!openAttribute)
  467. throw new InvalidOperationException("Token EndAttribute in state Start would result in an invalid XML document.");
  468. CheckState ();
  469. if (openXmlLang) {
  470. w.Write (xmlLang);
  471. openXmlLang = false;
  472. ((XmlTextWriterOpenElement) openElements [openElementCount - 1]).XmlLang = xmlLang;
  473. }
  474. if (openXmlSpace)
  475. {
  476. if (xmlSpace == XmlSpace.Preserve)
  477. w.Write ("preserve");
  478. else if (xmlSpace == XmlSpace.Default)
  479. w.Write ("default");
  480. openXmlSpace = false;
  481. ((XmlTextWriterOpenElement) openElements [openElementCount - 1]).XmlSpace = xmlSpace;
  482. }
  483. w.Write (quoteChar);
  484. openAttribute = false;
  485. if (saveAttributeValue) {
  486. if (savedAttributePrefix.Length > 0 && savingAttributeValue.Length == 0)
  487. throw new ArgumentException ("Cannot use prefix with an empty namespace.");
  488. // add namespace
  489. if (shouldAddSavedNsToManager) // not OLD one
  490. namespaceManager.AddNamespace (savedAttributePrefix, savingAttributeValue);
  491. userWrittenNamespaces [savedAttributePrefix] = savingAttributeValue;
  492. saveAttributeValue = false;
  493. savedAttributePrefix = String.Empty;
  494. savingAttributeValue = String.Empty;
  495. }
  496. }
  497. public override void WriteEndDocument ()
  498. {
  499. CloseOpenAttributeAndElements ();
  500. if (!hasRoot)
  501. throw new ArgumentException ("This document does not have a root element.");
  502. ws = WriteState.Start;
  503. hasRoot = false;
  504. }
  505. public override void WriteEndElement ()
  506. {
  507. WriteEndElementInternal (false);
  508. }
  509. private void WriteIndent ()
  510. {
  511. if (!indentLocal)
  512. return;
  513. w.Write (newLineChars);
  514. for (int i = 0; i < indentLevel; i++)
  515. w.Write (indentChars);
  516. }
  517. private void WriteEndElementInternal (bool fullEndElement)
  518. {
  519. if (openElementCount == 0)
  520. throw new InvalidOperationException("There was no XML start tag open.");
  521. if (openAttribute)
  522. WriteEndAttribute ();
  523. indentLevel--;
  524. CheckState ();
  525. AddMissingElementXmlns ();
  526. if (openStartElement) {
  527. if (openAttribute)
  528. WriteEndAttribute ();
  529. if (fullEndElement) {
  530. w.Write ('>');
  531. if (!ParentIndentingOverriden)
  532. WriteIndent ();
  533. w.Write ("</");
  534. XmlTextWriterOpenElement el = (XmlTextWriterOpenElement) openElements [openElementCount - 1];
  535. if (el.Prefix != String.Empty) {
  536. w.Write (el.Prefix);
  537. w.Write (':');
  538. }
  539. w.Write (el.LocalName);
  540. w.Write ('>');
  541. } else
  542. w.Write (" />");
  543. openElementCount--;
  544. openStartElement = false;
  545. } else {
  546. WriteIndent ();
  547. w.Write ("</");
  548. XmlTextWriterOpenElement el = (XmlTextWriterOpenElement) openElements [openElementCount - 1];
  549. openElementCount--;
  550. if (el.Prefix != String.Empty) {
  551. w.Write (el.Prefix);
  552. w.Write (':');
  553. }
  554. w.Write (el.LocalName);
  555. w.Write ('>');
  556. }
  557. namespaceManager.PopScope();
  558. }
  559. public override void WriteEntityRef (string name)
  560. {
  561. WriteRaw ("&");
  562. WriteStringInternal (name, true);
  563. WriteRaw (";");
  564. }
  565. public override void WriteFullEndElement ()
  566. {
  567. WriteEndElementInternal (true);
  568. }
  569. public override void WriteName (string name)
  570. {
  571. WriteNameInternal (name);
  572. }
  573. public override void WriteNmToken (string name)
  574. {
  575. WriteNmTokenInternal (name);
  576. }
  577. // LAMESPEC: It should reject such name that starts with "x" "m" "l" by XML specification, but
  578. // in fact it is used to write XmlDeclaration in WriteNode() (and it is inevitable since
  579. // WriteStartDocument() cannot specify encoding, while WriteNode() can write it).
  580. public override void WriteProcessingInstruction (string name, string text)
  581. {
  582. if ((name == null) || (name == string.Empty))
  583. throw new ArgumentException ("Argument processing instruction name must not be null or empty.");
  584. if (!XmlChar.IsName (name))
  585. throw new ArgumentException ("Invalid processing instruction name.");
  586. if ((text.IndexOf("?>") > 0))
  587. throw new ArgumentException ("Processing instruction cannot contain \"?>\" as its value.");
  588. CheckState ();
  589. CloseStartElement ();
  590. WriteIndent ();
  591. w.Write ("<?");
  592. w.Write (name);
  593. w.Write (' ');
  594. w.Write (text);
  595. w.Write ("?>");
  596. }
  597. public override void WriteQualifiedName (string localName, string ns)
  598. {
  599. if (!XmlChar.IsNCName (localName))
  600. throw new ArgumentException (String.Format ("Invalid local name '{0}'", localName));
  601. CheckState ();
  602. if (!openAttribute)
  603. CloseStartElement ();
  604. // WriteQualifiedName internal will reject such
  605. // qname whose namespace is not declared.
  606. string prefix = null;
  607. if (openAttribute && ns != String.Empty && LookupPrefix (ns) == null) {
  608. prefix = CheckNewPrefix (true, null, ns);
  609. namespaceManager.AddNamespace (prefix, ns);
  610. }
  611. WriteQualifiedNameInternal (localName, ns);
  612. if (prefix != null) {
  613. namespaceManager.RemoveNamespace (prefix, ns);
  614. newAttributeNamespaces [prefix] = ns;
  615. }
  616. }
  617. public override void WriteRaw (string data)
  618. {
  619. if (ws == WriteState.Start)
  620. ws = WriteState.Prolog;
  621. WriteStringInternal (data, false);
  622. }
  623. public override void WriteRaw (char[] buffer, int index, int count)
  624. {
  625. WriteRaw (new string (buffer, index, count));
  626. }
  627. public override void WriteStartAttribute (string prefix, string localName, string ns)
  628. {
  629. if (prefix == "xml") {
  630. // MS.NET looks to allow other names than
  631. // lang and space (e.g. xml:link, xml:hack).
  632. ns = XmlNamespaceManager.XmlnsXml;
  633. if (localName == "lang")
  634. openXmlLang = true;
  635. else if (localName == "space")
  636. openXmlSpace = true;
  637. }
  638. if (prefix == null)
  639. prefix = String.Empty;
  640. if (prefix.Length > 0 && (ns == null || ns.Length == 0))
  641. if (prefix != "xmlns")
  642. throw new ArgumentException ("Cannot use prefix with an empty namespace.");
  643. if (prefix == "xmlns") {
  644. if (localName == null || localName.Length == 0) {
  645. localName = prefix;
  646. prefix = String.Empty;
  647. }
  648. }
  649. // Note that null namespace with "xmlns" are allowed.
  650. #if NET_1_0
  651. if ((prefix == "xmlns" || localName == "xmlns" && prefix == String.Empty) && ns != XmlnsNamespace)
  652. #else
  653. if ((prefix == "xmlns" || localName == "xmlns" && prefix == String.Empty) && ns != null && ns != XmlnsNamespace)
  654. #endif
  655. throw new ArgumentException (String.Format ("The 'xmlns' attribute is bound to the reserved namespace '{0}'", XmlnsNamespace));
  656. CheckState ();
  657. if (ws == WriteState.Content)
  658. throw new InvalidOperationException ("Token StartAttribute in state " + WriteState + " would result in an invalid XML document.");
  659. if (prefix == null)
  660. prefix = String.Empty;
  661. if (ns == null)
  662. ns = String.Empty;
  663. string formatPrefix = "";
  664. if (ns != String.Empty && prefix != "xmlns") {
  665. string existingPrefix = namespaceManager.LookupPrefix (ns, false);
  666. if (existingPrefix == null || existingPrefix == "") {
  667. bool createPrefix = false;
  668. if (prefix == "")
  669. createPrefix = true;
  670. else {
  671. string existingNs = namespaceManager.LookupNamespace (prefix, false);
  672. if (existingNs != null) {
  673. namespaceManager.RemoveNamespace (prefix, existingNs);
  674. if (namespaceManager.LookupNamespace (prefix, false) != existingNs) {
  675. createPrefix = true;
  676. namespaceManager.AddNamespace (prefix, existingNs);
  677. }
  678. }
  679. }
  680. prefix = CheckNewPrefix (createPrefix, prefix, ns);
  681. }
  682. if (prefix == String.Empty && ns != XmlnsNamespace)
  683. prefix = (existingPrefix == null) ?
  684. String.Empty : existingPrefix;
  685. }
  686. if (prefix != String.Empty)
  687. {
  688. formatPrefix = prefix + ":";
  689. }
  690. if (openStartElement || attributeWrittenForElement) {
  691. if (newLineOnAttributes)
  692. WriteIndent ();
  693. else
  694. w.Write (" ");
  695. }
  696. w.Write (formatPrefix);
  697. w.Write (localName);
  698. w.Write ('=');
  699. w.Write (quoteChar);
  700. openAttribute = true;
  701. attributeWrittenForElement = true;
  702. ws = WriteState.Attribute;
  703. if (prefix == "xmlns" || prefix == String.Empty && localName == "xmlns") {
  704. if (prefix != openElementPrefix || openElementNS == null)
  705. shouldAddSavedNsToManager = true;
  706. saveAttributeValue = true;
  707. savedAttributePrefix = (prefix == "xmlns") ? localName : String.Empty;
  708. savingAttributeValue = String.Empty;
  709. }
  710. }
  711. private string CheckNewPrefix (bool createPrefix, string prefix, string ns)
  712. {
  713. do {
  714. if (createPrefix)
  715. prefix = "d" + indentLevel + "p" + (++autoCreatedPrefixes);
  716. createPrefix = false;
  717. // Check if prefix exists.
  718. // If yes - check if namespace is the same.
  719. if (newAttributeNamespaces [prefix] == null)
  720. newAttributeNamespaces.Add (prefix, ns);
  721. else if (!newAttributeNamespaces [prefix].Equals (ns))
  722. createPrefix = true;
  723. } while (createPrefix);
  724. return prefix;
  725. }
  726. public override void WriteStartDocument ()
  727. {
  728. WriteStartDocument ("");
  729. }
  730. public override void WriteStartDocument (bool standalone)
  731. {
  732. string standaloneFormatting;
  733. if (standalone == true)
  734. standaloneFormatting = String.Format (" standalone={0}yes{0}", quoteChar);
  735. else
  736. standaloneFormatting = String.Format (" standalone={0}no{0}", quoteChar);
  737. WriteStartDocument (standaloneFormatting);
  738. }
  739. private void WriteStartDocument (string standaloneFormatting)
  740. {
  741. if (documentStarted == true)
  742. throw new InvalidOperationException("WriteStartDocument should be the first call.");
  743. if (hasRoot)
  744. throw new XmlException ("WriteStartDocument called twice.");
  745. isDocumentEntity = true;
  746. // CheckState ();
  747. CheckOutputState ();
  748. string encodingFormatting = "";
  749. if (!nullEncoding)
  750. encodingFormatting = String.Format (" encoding={0}{1}{0}", quoteChar, w.Encoding.WebName);
  751. w.Write("<?xml version={0}1.0{0}{1}{2}?>", quoteChar, encodingFormatting, standaloneFormatting);
  752. ws = WriteState.Prolog;
  753. }
  754. public override void WriteStartElement (string prefix, string localName, string ns)
  755. {
  756. if (!Namespaces && (((prefix != null) && (prefix != String.Empty))
  757. || ((ns != null) && (ns != String.Empty))))
  758. throw new ArgumentException ("Cannot set the namespace if Namespaces is 'false'.");
  759. if ((prefix != null && prefix != String.Empty) && ((ns == null) || (ns == String.Empty)))
  760. throw new ArgumentException ("Cannot use a prefix with an empty namespace.");
  761. // ignore non-namespaced node's prefix.
  762. if (ns == null || ns == String.Empty)
  763. prefix = String.Empty;
  764. WriteStartElementInternal (prefix, localName, ns);
  765. }
  766. private void WriteStartElementInternal (string prefix, string localName, string ns)
  767. {
  768. CheckState ();
  769. hasRoot = true;
  770. CloseStartElement ();
  771. newAttributeNamespaces.Clear ();
  772. userWrittenNamespaces.Clear ();
  773. shouldCheckElementXmlns = false;
  774. if (prefix == null && ns != null)
  775. prefix = namespaceManager.LookupPrefix (ns, false);
  776. if (prefix == null)
  777. prefix = String.Empty;
  778. WriteIndent ();
  779. w.Write ('<');
  780. if (prefix != String.Empty) {
  781. w.Write (prefix);
  782. w.Write (':');
  783. }
  784. w.Write (localName);
  785. if (openElements.Count == openElementCount)
  786. openElements.Add (new XmlTextWriterOpenElement (prefix, localName));
  787. else
  788. ((XmlTextWriterOpenElement) openElements [openElementCount]).Reset (prefix, localName);
  789. openElementCount++;
  790. ws = WriteState.Element;
  791. openStartElement = true;
  792. openElementNS = ns;
  793. openElementPrefix = prefix;
  794. namespaceManager.PushScope ();
  795. indentLevel++;
  796. if (ns != null) {
  797. if (ns.Length > 0) {
  798. string existing = LookupPrefix (ns);
  799. if (existing != prefix) {
  800. shouldCheckElementXmlns = true;
  801. namespaceManager.AddNamespace (prefix, ns);
  802. }
  803. } else {
  804. if (ns != namespaceManager.DefaultNamespace) {
  805. shouldCheckElementXmlns = true;
  806. namespaceManager.AddNamespace ("", ns);
  807. }
  808. }
  809. }
  810. }
  811. public override void WriteString (string text)
  812. {
  813. switch (ws) {
  814. case WriteState.Start:
  815. case WriteState.Prolog:
  816. if (isDocumentEntity)
  817. throw new InvalidOperationException ("Token content in state Prolog would result in an invalid XML document.");
  818. ws = WriteState.Content;
  819. break;
  820. }
  821. WriteStringInternal (text, true);
  822. // MS.NET (1.0) saves attribute value only at WriteString.
  823. if (saveAttributeValue)
  824. // In most cases it will be called one time, so simply use string + string.
  825. savingAttributeValue += text;
  826. }
  827. string [] replacements = new string [] {
  828. "&amp;", "&lt;", "&gt;", "&quot;", "&apos;",
  829. "&#xD;", "&#xA;"};
  830. private string EscapeString (string source, bool outsideAttribute)
  831. {
  832. int start = 0;
  833. int pos = 0;
  834. int count = source.Length;
  835. char invalid = ' ';
  836. for (int i = 0; i < count; i++) {
  837. switch (source [i]) {
  838. case '&': pos = 0; break;
  839. case '<': pos = 1; break;
  840. case '>': pos = 2; break;
  841. case '\"':
  842. if (outsideAttribute) continue;
  843. if (QuoteChar == '\'') continue;
  844. pos = 3; break;
  845. case '\'':
  846. if (outsideAttribute) continue;
  847. if (QuoteChar == '\"') continue;
  848. pos = 4; break;
  849. case '\r':
  850. if (!normalizeNewLines && outsideAttribute)
  851. continue;
  852. pos = 5; break;
  853. case '\n':
  854. if (!normalizeNewLines && outsideAttribute)
  855. continue;
  856. pos = 6; break;
  857. default:
  858. if (XmlChar.IsInvalid (source [i])) {
  859. if (Char.IsSurrogate (source [i]) && source [i] < 0xDC00 &&
  860. i + 1 < count && Char.IsSurrogate (source [i + 1]) && source [i + 1] >= 0xDC00) {
  861. // A legitimate UTF-16 surrogate pair; let it through.
  862. i++;
  863. continue;
  864. } else {
  865. if (checkCharacters)
  866. throw new ArgumentException (String.Format ("Character hexadecimal value {0:4x} is invalid.", (int) source [i]));
  867. invalid = source [i];
  868. pos = -1;
  869. break;
  870. }
  871. }
  872. else
  873. continue;
  874. }
  875. if (cachedStringBuilder == null)
  876. cachedStringBuilder = new StringBuilder ();
  877. cachedStringBuilder.Append (source.Substring (start, i - start));
  878. if (pos < 0) {
  879. cachedStringBuilder.Append ("&#x");
  880. // if (invalid < (char) 255)
  881. // cachedStringBuilder.Append (((int) invalid).ToString ("X02", CultureInfo.InvariantCulture));
  882. // else
  883. // cachedStringBuilder.Append (((int) invalid).ToString ("X04", CultureInfo.InvariantCulture));
  884. cachedStringBuilder.Append (((int) invalid).ToString ("X", CultureInfo.InvariantCulture));
  885. cachedStringBuilder.Append (";");
  886. }
  887. #if NET_2_0
  888. else if (outsideAttribute && pos >= 5) {
  889. cachedStringBuilder.Append (newLineChars);
  890. // all \r,\n,\r\n are replaced with
  891. // NewLineChars, so \n after \r should
  892. // be consumed here.
  893. if (pos == 5 && i + 1 < count && source [i + 1] == '\n')
  894. i++;
  895. }
  896. #endif
  897. else
  898. cachedStringBuilder.Append (replacements [pos]);
  899. start = i + 1;
  900. }
  901. if (start == 0)
  902. return source;
  903. else if (start < count)
  904. cachedStringBuilder.Append (source.Substring (start, count - start));
  905. string s = cachedStringBuilder.ToString ();
  906. cachedStringBuilder.Length = 0;
  907. return s;
  908. }
  909. private void WriteStringInternal (string text, bool entitize)
  910. {
  911. if (text == null)
  912. text = String.Empty;
  913. if (text != String.Empty) {
  914. CheckState ();
  915. if (entitize)
  916. text = EscapeString (text, !openAttribute);
  917. if (!openAttribute)
  918. {
  919. IndentingOverriden = true;
  920. CloseStartElement ();
  921. }
  922. if (!openXmlLang && !openXmlSpace)
  923. w.Write (text);
  924. else
  925. {
  926. if (openXmlLang)
  927. xmlLang = text;
  928. else
  929. {
  930. switch (text)
  931. {
  932. case "default":
  933. xmlSpace = XmlSpace.Default;
  934. break;
  935. case "preserve":
  936. xmlSpace = XmlSpace.Preserve;
  937. break;
  938. default:
  939. throw new ArgumentException ("'{0}' is an invalid xml:space value.");
  940. }
  941. }
  942. }
  943. }
  944. }
  945. public override void WriteSurrogateCharEntity (char lowChar, char highChar)
  946. {
  947. if (lowChar < '\uDC00' || lowChar > '\uDFFF' ||
  948. highChar < '\uD800' || highChar > '\uDBFF')
  949. throw new ArgumentException ("Invalid (low, high) pair of characters was specified.");
  950. CheckState ();
  951. if (!openAttribute) {
  952. IndentingOverriden = true;
  953. CloseStartElement ();
  954. }
  955. w.Write ("&#x");
  956. w.Write (((int) ((highChar - 0xD800) * 0x400 + (lowChar - 0xDC00) + 0x10000)).ToString ("X", CultureInfo.InvariantCulture));
  957. w.Write (';');
  958. }
  959. public override void WriteWhitespace (string ws)
  960. {
  961. if (!XmlChar.IsWhitespace (ws))
  962. throw new ArgumentException ("Invalid Whitespace");
  963. CheckState ();
  964. if (!openAttribute) {
  965. IndentingOverriden = true;
  966. CloseStartElement ();
  967. }
  968. w.Write (ws);
  969. }
  970. #endregion
  971. }
  972. }