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