XmlTextWriter.cs 30 KB

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