XmlTextWriter.cs 28 KB

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