XmlTextWriter.cs 30 KB

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