XmlTextWriter.cs 30 KB

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