XmlTextWriter.cs 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  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. XmlTextWriterOpenElement [] openElements =
  52. new XmlTextWriterOpenElement [20];
  53. int openElementCount;
  54. Formatting formatting = Formatting.None;
  55. int indentation = 2;
  56. char indentChar = ' ';
  57. string indentChars = " ";
  58. char quoteChar = '\"';
  59. int indentLevel = 0;
  60. bool indentLocal;
  61. Stream baseStream = null;
  62. string xmlLang = null;
  63. XmlSpace xmlSpace = XmlSpace.None;
  64. bool openXmlLang = false;
  65. bool openXmlSpace = false;
  66. string openElementPrefix;
  67. string openElementNS;
  68. bool hasRoot = false;
  69. bool isDocumentEntity = false;
  70. Hashtable newAttributeNamespaces = new Hashtable ();
  71. Hashtable userWrittenNamespaces = new Hashtable ();
  72. StringBuilder cachedStringBuilder;
  73. int autoCreatedPrefixes;
  74. XmlNamespaceManager namespaceManager = new XmlNamespaceManager (new NameTable ());
  75. string savingAttributeValue = String.Empty;
  76. bool saveAttributeValue;
  77. string savedAttributePrefix;
  78. bool shouldAddSavedNsToManager;
  79. bool shouldCheckElementXmlns;
  80. // XmlWriterSettings support
  81. bool checkCharacters;
  82. bool closeOutput = true;
  83. bool newLineOnAttributes;
  84. string newLineChars;
  85. #if NET_2_0
  86. bool outputXmlDeclaration;
  87. ConformanceLevel conformanceLevel;
  88. #endif
  89. #endregion
  90. #region Constructors
  91. public XmlTextWriter (TextWriter w) : base ()
  92. {
  93. this.w = w;
  94. nullEncoding = (w.Encoding == null);
  95. StreamWriter sw = w as StreamWriter;
  96. if (sw != null)
  97. baseStream = sw.BaseStream;
  98. newLineChars = w.NewLine;
  99. }
  100. public XmlTextWriter (Stream w, Encoding encoding) : base ()
  101. {
  102. if (encoding == null) {
  103. nullEncoding = true;
  104. this.w = new StreamWriter (w);
  105. } else
  106. this.w = new StreamWriter (w, encoding);
  107. baseStream = w;
  108. newLineChars = this.w.NewLine;
  109. }
  110. public XmlTextWriter (string filename, Encoding encoding) :
  111. this (new FileStream (filename, FileMode.Create, FileAccess.Write, FileShare.None), encoding)
  112. {
  113. }
  114. #endregion
  115. #region Properties
  116. public Stream BaseStream {
  117. get { return baseStream; }
  118. }
  119. public Formatting Formatting {
  120. get { return formatting; }
  121. set { formatting = value; }
  122. }
  123. private bool IndentingOverriden
  124. {
  125. get {
  126. if (openElementCount == 0)
  127. return false;
  128. else
  129. return openElements [openElementCount - 1].IndentingOverriden;
  130. }
  131. set {
  132. if (openElementCount > 0)
  133. openElements [openElementCount - 1].IndentingOverriden = value;
  134. }
  135. }
  136. private bool ParentIndentingOverriden {
  137. get {
  138. if (openElementCount < 2)
  139. return false;
  140. return 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 = 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 = 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 wrong output.");
  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. CheckState ();
  440. if (ws != WriteState.Start && ws != WriteState.Prolog)
  441. throw new InvalidOperationException (String.Format ("Doctype is not allowed at '{0}' state.", ws));
  442. if (documentStarted && formatting == Formatting.Indented)
  443. w.WriteLine ();
  444. w.Write ("<!DOCTYPE ");
  445. w.Write (name);
  446. if (pubid != null) {
  447. w.Write (" PUBLIC ");
  448. w.Write (quoteChar);
  449. w.Write (pubid);
  450. w.Write (quoteChar);
  451. w.Write (' ');
  452. w.Write (quoteChar);
  453. w.Write (sysid);
  454. w.Write (quoteChar);
  455. } else if (sysid != null) {
  456. w.Write (" SYSTEM ");
  457. w.Write (quoteChar);
  458. w.Write (sysid);
  459. w.Write (quoteChar);
  460. }
  461. if (subset != null) {
  462. w.Write ('[');
  463. w.Write (subset);
  464. w.Write (']');
  465. }
  466. w.Write('>');
  467. ws = WriteState.Element;
  468. }
  469. public override void WriteEndAttribute ()
  470. {
  471. if (!openAttribute)
  472. throw InvalidOperationError ("Token EndAttribute in state Start would result in an invalid XML document.");
  473. CheckState ();
  474. if (openXmlLang) {
  475. w.Write (xmlLang);
  476. openXmlLang = false;
  477. if (openElementCount > 0)
  478. openElements [openElementCount - 1].XmlLang = xmlLang;
  479. }
  480. if (openXmlSpace)
  481. {
  482. if (xmlSpace == XmlSpace.Preserve)
  483. w.Write ("preserve");
  484. else if (xmlSpace == XmlSpace.Default)
  485. w.Write ("default");
  486. openXmlSpace = false;
  487. if (openElementCount > 0)
  488. openElements [openElementCount - 1].XmlSpace = xmlSpace;
  489. }
  490. w.Write (quoteChar);
  491. openAttribute = false;
  492. if (saveAttributeValue) {
  493. if (savedAttributePrefix.Length > 0 && savingAttributeValue.Length == 0)
  494. throw ArgumentError ("Cannot use prefix with an empty namespace.");
  495. // add namespace
  496. if (shouldAddSavedNsToManager) // not OLD one
  497. namespaceManager.AddNamespace (savedAttributePrefix, savingAttributeValue);
  498. userWrittenNamespaces [savedAttributePrefix] = savingAttributeValue;
  499. saveAttributeValue = false;
  500. savedAttributePrefix = String.Empty;
  501. savingAttributeValue = String.Empty;
  502. }
  503. }
  504. public override void WriteEndDocument ()
  505. {
  506. CloseOpenAttributeAndElements ();
  507. if (!hasRoot)
  508. throw ArgumentError ("This document does not have a root element.");
  509. ws = WriteState.Start;
  510. hasRoot = false;
  511. }
  512. public override void WriteEndElement ()
  513. {
  514. WriteEndElementInternal (false);
  515. }
  516. private void WriteIndent ()
  517. {
  518. if (!indentLocal)
  519. return;
  520. w.Write (newLineChars);
  521. for (int i = 0; i < indentLevel; i++)
  522. w.Write (indentChars);
  523. }
  524. private void WriteEndElementInternal (bool fullEndElement)
  525. {
  526. if (openElementCount == 0)
  527. throw InvalidOperationError ("There was no XML start tag open.");
  528. if (openAttribute)
  529. WriteEndAttribute ();
  530. indentLevel--;
  531. CheckState ();
  532. AddMissingElementXmlns ();
  533. if (openStartElement) {
  534. if (openAttribute)
  535. WriteEndAttribute ();
  536. if (fullEndElement) {
  537. w.Write ('>');
  538. if (!ParentIndentingOverriden)
  539. WriteIndent ();
  540. w.Write ("</");
  541. XmlTextWriterOpenElement el = openElements [openElementCount - 1];
  542. if (el.Prefix != String.Empty) {
  543. w.Write (el.Prefix);
  544. w.Write (':');
  545. }
  546. w.Write (el.LocalName);
  547. w.Write ('>');
  548. } else
  549. w.Write (" />");
  550. openElementCount--;
  551. openStartElement = false;
  552. } else {
  553. WriteIndent ();
  554. w.Write ("</");
  555. XmlTextWriterOpenElement el = openElements [openElementCount - 1];
  556. openElementCount--;
  557. if (el.Prefix != String.Empty) {
  558. w.Write (el.Prefix);
  559. w.Write (':');
  560. }
  561. w.Write (el.LocalName);
  562. w.Write ('>');
  563. }
  564. namespaceManager.PopScope();
  565. }
  566. public override void WriteEntityRef (string name)
  567. {
  568. WriteRaw ("&");
  569. WriteStringInternal (name, true);
  570. WriteRaw (";");
  571. }
  572. public override void WriteFullEndElement ()
  573. {
  574. WriteEndElementInternal (true);
  575. }
  576. public override void WriteName (string name)
  577. {
  578. WriteNameInternal (name);
  579. }
  580. public override void WriteNmToken (string name)
  581. {
  582. if (name == null || name.Length == 0)
  583. throw ArgumentError ("The Name cannot be empty.");
  584. WriteNmTokenInternal (name);
  585. }
  586. // LAMESPEC: It should reject such name that starts with "x" "m" "l" by XML specification, but
  587. // in fact it is used to write XmlDeclaration in WriteNode() (and it is inevitable since
  588. // WriteStartDocument() cannot specify encoding, while WriteNode() can write it).
  589. public override void WriteProcessingInstruction (string name, string text)
  590. {
  591. if ((name == null) || (name == string.Empty))
  592. throw ArgumentError ("Argument processing instruction name must not be null or empty.");
  593. if (!XmlChar.IsName (name))
  594. throw ArgumentError ("Invalid processing instruction name.");
  595. if ((text.IndexOf("?>") > 0))
  596. throw ArgumentError ("Processing instruction cannot contain \"?>\" as its value.");
  597. CheckOutputState ();
  598. CloseStartElement ();
  599. WriteIndent ();
  600. w.Write ("<?");
  601. w.Write (name);
  602. w.Write (' ');
  603. w.Write (text);
  604. w.Write ("?>");
  605. if (ws == WriteState.Start)
  606. ws = WriteState.Prolog;
  607. }
  608. public override void WriteQualifiedName (string localName, string ns)
  609. {
  610. if (!XmlChar.IsNCName (localName))
  611. throw ArgumentError (String.Format ("Invalid local name '{0}'", localName));
  612. CheckState ();
  613. if (!openAttribute)
  614. CloseStartElement ();
  615. // WriteQualifiedName internal will reject such
  616. // qname whose namespace is not declared.
  617. string prefix = null;
  618. if (openAttribute && ns != String.Empty && LookupPrefix (ns) == null) {
  619. prefix = CheckNewPrefix (true, null, ns);
  620. namespaceManager.AddNamespace (prefix, ns);
  621. }
  622. WriteQualifiedNameInternal (localName, ns);
  623. if (prefix != null) {
  624. namespaceManager.RemoveNamespace (prefix, ns);
  625. newAttributeNamespaces [prefix] = ns;
  626. }
  627. }
  628. public override void WriteRaw (string data)
  629. {
  630. if (ws == WriteState.Start)
  631. ws = WriteState.Prolog;
  632. WriteStringInternal (data, false);
  633. }
  634. public override void WriteRaw (char[] buffer, int index, int count)
  635. {
  636. WriteRaw (new string (buffer, index, count));
  637. }
  638. public override void WriteStartAttribute (string prefix, string localName, string ns)
  639. {
  640. if (prefix == null)
  641. prefix = String.Empty;
  642. else if (prefix == "xml") {
  643. ns = XmlNamespaceManager.XmlnsXml;
  644. if (localName == "lang")
  645. openXmlLang = true;
  646. else if (localName == "space")
  647. openXmlSpace = true;
  648. }
  649. if (prefix.Length > 0 && (ns == null || ns.Length == 0))
  650. if (prefix != "xmlns")
  651. throw ArgumentError ("Cannot use prefix with an empty namespace.");
  652. if (prefix == "xmlns") {
  653. if (localName == null || localName.Length == 0) {
  654. localName = prefix;
  655. prefix = String.Empty;
  656. }
  657. }
  658. // Note that null namespace with "xmlns" are allowed.
  659. if ((prefix == "xmlns" || localName == "xmlns" && prefix == String.Empty) && ns != null && ns != XmlnsNamespace)
  660. throw ArgumentError (String.Format ("The 'xmlns' attribute is bound to the reserved namespace '{0}'", XmlnsNamespace));
  661. if (ns == XmlnsNamespace) // see bug #77083
  662. prefix = localName == "xmlns" ? String.Empty : "xmlns";
  663. CheckState ();
  664. if (ws == WriteState.Content)
  665. throw InvalidOperationError (String.Format ("Token StartAttribute in state {0} would result in an invalid XML document.", ws));
  666. if (prefix == null)
  667. prefix = String.Empty;
  668. if (ns == null)
  669. ns = String.Empty;
  670. string formatPrefix = "";
  671. if (ns != String.Empty && prefix != "xmlns") {
  672. string existingPrefix = GetExistingPrefix (ns);
  673. if (existingPrefix == null || existingPrefix == "") {
  674. bool createPrefix = false;
  675. if (prefix == "")
  676. createPrefix = true;
  677. else {
  678. string existingNs = namespaceManager.LookupNamespace (prefix, false);
  679. if (existingNs != null) {
  680. namespaceManager.RemoveNamespace (prefix, existingNs);
  681. if (namespaceManager.LookupNamespace (prefix, false) != existingNs) {
  682. createPrefix = true;
  683. namespaceManager.AddNamespace (prefix, existingNs);
  684. }
  685. }
  686. }
  687. prefix = CheckNewPrefix (createPrefix, prefix, ns);
  688. }
  689. if (prefix == String.Empty && ns != XmlnsNamespace)
  690. prefix = (existingPrefix == null) ?
  691. String.Empty : existingPrefix;
  692. }
  693. if (prefix != String.Empty)
  694. {
  695. formatPrefix = prefix + ":";
  696. }
  697. if (openStartElement || attributeWrittenForElement) {
  698. if (newLineOnAttributes)
  699. WriteIndent ();
  700. else
  701. w.Write (" ");
  702. }
  703. w.Write (formatPrefix);
  704. w.Write (localName);
  705. w.Write ('=');
  706. w.Write (quoteChar);
  707. openAttribute = true;
  708. attributeWrittenForElement = true;
  709. ws = WriteState.Attribute;
  710. if (prefix == "xmlns" || prefix == String.Empty && localName == "xmlns") {
  711. if (prefix != openElementPrefix || openElementNS == null)
  712. shouldAddSavedNsToManager = true;
  713. saveAttributeValue = true;
  714. savedAttributePrefix = (prefix == "xmlns") ? localName : String.Empty;
  715. savingAttributeValue = String.Empty;
  716. }
  717. }
  718. string GetExistingPrefix (string ns)
  719. {
  720. if (newAttributeNamespaces.ContainsValue (ns))
  721. foreach (DictionaryEntry de in newAttributeNamespaces)
  722. if (de.Value as string == ns)
  723. return (string) de.Key;
  724. return namespaceManager.LookupPrefix (ns, false);
  725. }
  726. private string CheckNewPrefix (bool createPrefix, string prefix, string ns)
  727. {
  728. do {
  729. if (createPrefix)
  730. prefix = "d" + indentLevel + "p" + (++autoCreatedPrefixes);
  731. createPrefix = false;
  732. // Check if prefix exists.
  733. // If yes - check if namespace is the same.
  734. if (newAttributeNamespaces [prefix] == null)
  735. newAttributeNamespaces.Add (prefix, ns);
  736. else if (!newAttributeNamespaces [prefix].Equals (ns))
  737. createPrefix = true;
  738. } while (createPrefix);
  739. return prefix;
  740. }
  741. public override void WriteStartDocument ()
  742. {
  743. WriteStartDocument ("");
  744. }
  745. public override void WriteStartDocument (bool standalone)
  746. {
  747. string standaloneFormatting;
  748. if (standalone == true)
  749. standaloneFormatting = String.Format (" standalone={0}yes{0}", quoteChar);
  750. else
  751. standaloneFormatting = String.Format (" standalone={0}no{0}", quoteChar);
  752. WriteStartDocument (standaloneFormatting);
  753. }
  754. private void WriteStartDocument (string standaloneFormatting)
  755. {
  756. if (documentStarted == true)
  757. throw InvalidOperationError ("WriteStartDocument should be the first call.");
  758. if (hasRoot)
  759. throw XmlError ("WriteStartDocument called twice.");
  760. isDocumentEntity = true;
  761. // CheckState ();
  762. CheckOutputState ();
  763. string encodingFormatting = "";
  764. if (!nullEncoding)
  765. encodingFormatting = String.Format (" encoding={0}{1}{0}", quoteChar, w.Encoding.WebName);
  766. w.Write("<?xml version={0}1.0{0}{1}{2}?>", quoteChar, encodingFormatting, standaloneFormatting);
  767. ws = WriteState.Prolog;
  768. }
  769. public override void WriteStartElement (string prefix, string localName, string ns)
  770. {
  771. if (!Namespaces && (((prefix != null) && (prefix != String.Empty))
  772. || ((ns != null) && (ns != String.Empty))))
  773. throw ArgumentError ("Cannot set the namespace if Namespaces is 'false'.");
  774. if ((prefix != null && prefix.Length > 0) && ((ns == null)))
  775. throw ArgumentError ("Cannot use a prefix with an empty namespace.");
  776. // Considering the fact that WriteStartAttribute()
  777. // automatically changes argument namespaceURI, this
  778. // is kind of silly implementation. See bug #77094.
  779. if (Namespaces &&
  780. ns != XmlNamespaceManager.XmlnsXml &&
  781. prefix != null && prefix.Length == 3 &&
  782. (prefix [0] == 'x' || prefix [0] == 'X') &&
  783. (prefix [1] == 'm' || prefix [1] == 'M') &&
  784. (prefix [2] == 'l' || prefix [2] == 'L'))
  785. throw new ArgumentException ("A prefix cannot be equivalent to \"xml\" in case-insensitive match.");
  786. // ignore non-namespaced node's prefix.
  787. if (ns == null || ns == String.Empty)
  788. prefix = String.Empty;
  789. WriteStartElementInternal (prefix, localName, ns);
  790. }
  791. private void WriteStartElementInternal (string prefix, string localName, string ns)
  792. {
  793. CheckState ();
  794. hasRoot = true;
  795. CloseStartElement ();
  796. newAttributeNamespaces.Clear ();
  797. userWrittenNamespaces.Clear ();
  798. shouldCheckElementXmlns = false;
  799. if (prefix == null && ns != null)
  800. prefix = namespaceManager.LookupPrefix (ns, false);
  801. if (prefix == null)
  802. prefix = String.Empty;
  803. WriteIndent ();
  804. w.Write ('<');
  805. if (prefix != String.Empty) {
  806. w.Write (prefix);
  807. w.Write (':');
  808. }
  809. w.Write (localName);
  810. if (openElements.Length == openElementCount) {
  811. XmlTextWriterOpenElement [] tmp =
  812. new XmlTextWriterOpenElement [openElementCount * 2];
  813. Array.Copy (openElements, tmp, openElementCount);
  814. openElements = tmp;
  815. }
  816. if (openElements [openElementCount] == null)
  817. openElements [openElementCount] =
  818. new XmlTextWriterOpenElement (prefix, localName);
  819. else
  820. openElements [openElementCount].Reset (prefix, localName);
  821. openElementCount++;
  822. ws = WriteState.Element;
  823. openStartElement = true;
  824. openElementNS = ns;
  825. openElementPrefix = prefix;
  826. namespaceManager.PushScope ();
  827. indentLevel++;
  828. if (ns != null) {
  829. if (ns.Length > 0) {
  830. string existing = LookupPrefix (ns);
  831. if (existing != prefix) {
  832. shouldCheckElementXmlns = true;
  833. namespaceManager.AddNamespace (prefix, ns);
  834. }
  835. } else {
  836. if (ns != namespaceManager.DefaultNamespace) {
  837. shouldCheckElementXmlns = true;
  838. namespaceManager.AddNamespace ("", ns);
  839. }
  840. }
  841. }
  842. }
  843. public override void WriteString (string text)
  844. {
  845. switch (ws) {
  846. case WriteState.Start:
  847. case WriteState.Prolog:
  848. if (isDocumentEntity)
  849. throw InvalidOperationError ("Token content in state Prolog would result in an invalid XML document.");
  850. ws = WriteState.Content;
  851. break;
  852. }
  853. WriteStringInternal (text, true);
  854. // MS.NET (1.0) saves attribute value only at WriteString.
  855. if (saveAttributeValue)
  856. // In most cases it will be called one time, so simply use string + string.
  857. savingAttributeValue += text;
  858. }
  859. string [] replacements = new string [] {
  860. "&amp;", "&lt;", "&gt;", "&quot;", "&apos;",
  861. "&#xD;", "&#xA;"};
  862. private string EscapeString (string source, bool outsideAttribute)
  863. {
  864. int start = 0;
  865. int pos = 0;
  866. int count = source.Length;
  867. char invalid = ' ';
  868. for (int i = 0; i < count; i++) {
  869. switch (source [i]) {
  870. case '&': pos = 0; break;
  871. case '<': pos = 1; break;
  872. case '>': pos = 2; break;
  873. case '\"':
  874. if (outsideAttribute) continue;
  875. if (QuoteChar == '\'') continue;
  876. pos = 3; break;
  877. case '\'':
  878. if (outsideAttribute) continue;
  879. if (QuoteChar == '\"') continue;
  880. pos = 4; break;
  881. case '\r':
  882. if (outsideAttribute)
  883. continue;
  884. pos = 5; break;
  885. case '\n':
  886. if (outsideAttribute)
  887. continue;
  888. pos = 6; break;
  889. default:
  890. if (XmlChar.IsInvalid (source [i])) {
  891. if (Char.IsSurrogate (source [i]) && source [i] < 0xDC00 &&
  892. i + 1 < count && Char.IsSurrogate (source [i + 1]) && source [i + 1] >= 0xDC00) {
  893. // A legitimate UTF-16 surrogate pair; let it through.
  894. i++;
  895. continue;
  896. } else {
  897. if (checkCharacters)
  898. throw ArgumentError (String.Format ("Character hexadecimal value {0:4x} is invalid.", (int) source [i]));
  899. invalid = source [i];
  900. pos = -1;
  901. break;
  902. }
  903. }
  904. else
  905. continue;
  906. }
  907. if (cachedStringBuilder == null)
  908. cachedStringBuilder = new StringBuilder ();
  909. cachedStringBuilder.Append (source.Substring (start, i - start));
  910. if (pos < 0) {
  911. cachedStringBuilder.Append ("&#x");
  912. // if (invalid < (char) 255)
  913. // cachedStringBuilder.Append (((int) invalid).ToString ("X02", CultureInfo.InvariantCulture));
  914. // else
  915. // cachedStringBuilder.Append (((int) invalid).ToString ("X04", CultureInfo.InvariantCulture));
  916. cachedStringBuilder.Append (((int) invalid).ToString ("X", CultureInfo.InvariantCulture));
  917. cachedStringBuilder.Append (";");
  918. }
  919. #if NET_2_0
  920. else if (outsideAttribute && pos >= 5) {
  921. cachedStringBuilder.Append (newLineChars);
  922. // all \r,\n,\r\n are replaced with
  923. // NewLineChars, so \n after \r should
  924. // be consumed here.
  925. if (pos == 5 && i + 1 < count && source [i + 1] == '\n')
  926. i++;
  927. }
  928. #endif
  929. else
  930. cachedStringBuilder.Append (replacements [pos]);
  931. start = i + 1;
  932. }
  933. if (start == 0)
  934. return source;
  935. else if (start < count)
  936. cachedStringBuilder.Append (source.Substring (start, count - start));
  937. string s = cachedStringBuilder.ToString ();
  938. cachedStringBuilder.Length = 0;
  939. return s;
  940. }
  941. private void WriteStringInternal (string text, bool entitize)
  942. {
  943. if (text == null || text.Length == 0 && entitize)
  944. return;
  945. CheckState ();
  946. if (entitize)
  947. text = EscapeString (text, !openAttribute);
  948. if (!openAttribute)
  949. {
  950. IndentingOverriden = true;
  951. CloseStartElement ();
  952. }
  953. if (!openXmlLang && !openXmlSpace)
  954. w.Write (text);
  955. else
  956. {
  957. if (openXmlLang)
  958. xmlLang = text;
  959. else
  960. {
  961. switch (text)
  962. {
  963. case "default":
  964. xmlSpace = XmlSpace.Default;
  965. break;
  966. case "preserve":
  967. xmlSpace = XmlSpace.Preserve;
  968. break;
  969. default:
  970. throw ArgumentError ("'{0}' is an invalid xml:space value.");
  971. }
  972. }
  973. }
  974. }
  975. public override void WriteSurrogateCharEntity (char lowChar, char highChar)
  976. {
  977. if (lowChar < '\uDC00' || lowChar > '\uDFFF' ||
  978. highChar < '\uD800' || highChar > '\uDBFF')
  979. throw ArgumentError ("Invalid (low, high) pair of characters was specified.");
  980. CheckState ();
  981. if (!openAttribute) {
  982. IndentingOverriden = true;
  983. CloseStartElement ();
  984. }
  985. w.Write ("&#x");
  986. w.Write (((int) ((highChar - 0xD800) * 0x400 + (lowChar - 0xDC00) + 0x10000)).ToString ("X", CultureInfo.InvariantCulture));
  987. w.Write (';');
  988. }
  989. public override void WriteWhitespace (string value)
  990. {
  991. if (value == null || value.Length == 0) {
  992. throw ArgumentError ("Only white space characters should be used.");
  993. }
  994. if (!XmlChar.IsWhitespace (value))
  995. throw ArgumentError ("Invalid Whitespace");
  996. CheckState ();
  997. if (!openAttribute) {
  998. IndentingOverriden = true;
  999. CloseStartElement ();
  1000. }
  1001. w.Write (value);
  1002. if (ws == WriteState.Start)
  1003. ws = WriteState.Prolog;
  1004. }
  1005. private Exception ArgumentError (string message)
  1006. {
  1007. #if NET_2_0
  1008. ws = WriteState.Error;
  1009. #endif
  1010. return new ArgumentException (message);
  1011. }
  1012. private Exception ArgumentError (string message, string name)
  1013. {
  1014. #if NET_2_0
  1015. ws = WriteState.Error;
  1016. #endif
  1017. return new ArgumentException (message);
  1018. }
  1019. private Exception InvalidOperationError (string message)
  1020. {
  1021. #if NET_2_0
  1022. ws = WriteState.Error;
  1023. #endif
  1024. return new InvalidOperationException (message);
  1025. }
  1026. private Exception XmlError (string message)
  1027. {
  1028. #if NET_2_0
  1029. ws = WriteState.Error;
  1030. #endif
  1031. return new XmlException (message);
  1032. }
  1033. #endregion
  1034. }
  1035. }