XmlTextWriter.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  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. if (name == null || name.Length == 0)
  579. throw ArgumentError ("The Name cannot be empty.");
  580. WriteNmTokenInternal (name);
  581. }
  582. // LAMESPEC: It should reject such name that starts with "x" "m" "l" by XML specification, but
  583. // in fact it is used to write XmlDeclaration in WriteNode() (and it is inevitable since
  584. // WriteStartDocument() cannot specify encoding, while WriteNode() can write it).
  585. public override void WriteProcessingInstruction (string name, string text)
  586. {
  587. if ((name == null) || (name == string.Empty))
  588. throw ArgumentError ("Argument processing instruction name must not be null or empty.");
  589. if (!XmlChar.IsName (name))
  590. throw ArgumentError ("Invalid processing instruction name.");
  591. if ((text.IndexOf("?>") > 0))
  592. throw ArgumentError ("Processing instruction cannot contain \"?>\" as its value.");
  593. CheckState ();
  594. CloseStartElement ();
  595. WriteIndent ();
  596. w.Write ("<?");
  597. w.Write (name);
  598. w.Write (' ');
  599. w.Write (text);
  600. w.Write ("?>");
  601. }
  602. public override void WriteQualifiedName (string localName, string ns)
  603. {
  604. if (!XmlChar.IsNCName (localName))
  605. throw ArgumentError (String.Format ("Invalid local name '{0}'", localName));
  606. CheckState ();
  607. if (!openAttribute)
  608. CloseStartElement ();
  609. // WriteQualifiedName internal will reject such
  610. // qname whose namespace is not declared.
  611. string prefix = null;
  612. if (openAttribute && ns != String.Empty && LookupPrefix (ns) == null) {
  613. prefix = CheckNewPrefix (true, null, ns);
  614. namespaceManager.AddNamespace (prefix, ns);
  615. }
  616. WriteQualifiedNameInternal (localName, ns);
  617. if (prefix != null) {
  618. namespaceManager.RemoveNamespace (prefix, ns);
  619. newAttributeNamespaces [prefix] = ns;
  620. }
  621. }
  622. public override void WriteRaw (string data)
  623. {
  624. if (ws == WriteState.Start)
  625. ws = WriteState.Prolog;
  626. WriteStringInternal (data, false);
  627. }
  628. public override void WriteRaw (char[] buffer, int index, int count)
  629. {
  630. WriteRaw (new string (buffer, index, count));
  631. }
  632. public override void WriteStartAttribute (string prefix, string localName, string ns)
  633. {
  634. if (prefix == "xml") {
  635. // MS.NET looks to allow other names than
  636. // lang and space (e.g. xml:link, xml:hack).
  637. ns = XmlNamespaceManager.XmlnsXml;
  638. if (localName == "lang")
  639. openXmlLang = true;
  640. else if (localName == "space")
  641. openXmlSpace = true;
  642. }
  643. if (prefix == null)
  644. prefix = String.Empty;
  645. if (prefix.Length > 0 && (ns == null || ns.Length == 0))
  646. if (prefix != "xmlns")
  647. throw ArgumentError ("Cannot use prefix with an empty namespace.");
  648. if (prefix == "xmlns") {
  649. if (localName == null || localName.Length == 0) {
  650. localName = prefix;
  651. prefix = String.Empty;
  652. }
  653. }
  654. // Note that null namespace with "xmlns" are allowed.
  655. #if NET_1_0
  656. if ((prefix == "xmlns" || localName == "xmlns" && prefix == String.Empty) && ns != XmlnsNamespace)
  657. #else
  658. if ((prefix == "xmlns" || localName == "xmlns" && prefix == String.Empty) && ns != null && ns != XmlnsNamespace)
  659. #endif
  660. throw ArgumentError (String.Format ("The 'xmlns' attribute is bound to the reserved namespace '{0}'", XmlnsNamespace));
  661. if (ns == XmlnsNamespace) // see bug #77083
  662. prefix = localName == "xmlns" ? String.Empty : "xmlns";
  663. CheckState ();
  664. if (ws == WriteState.Content)
  665. throw InvalidOperationError (String.Format ("Token StartAttribute in state {0} would result in an invalid XML document.", ws));
  666. if (prefix == null)
  667. prefix = String.Empty;
  668. if (ns == null)
  669. ns = String.Empty;
  670. string formatPrefix = "";
  671. if (ns != String.Empty && prefix != "xmlns") {
  672. string existingPrefix = namespaceManager.LookupPrefix (ns, false);
  673. if (existingPrefix == null || existingPrefix == "") {
  674. bool createPrefix = false;
  675. if (prefix == "")
  676. createPrefix = true;
  677. else {
  678. string existingNs = namespaceManager.LookupNamespace (prefix, false);
  679. if (existingNs != null) {
  680. namespaceManager.RemoveNamespace (prefix, existingNs);
  681. if (namespaceManager.LookupNamespace (prefix, false) != existingNs) {
  682. createPrefix = true;
  683. namespaceManager.AddNamespace (prefix, existingNs);
  684. }
  685. }
  686. }
  687. prefix = CheckNewPrefix (createPrefix, prefix, ns);
  688. }
  689. if (prefix == String.Empty && ns != XmlnsNamespace)
  690. prefix = (existingPrefix == null) ?
  691. String.Empty : existingPrefix;
  692. }
  693. if (prefix != String.Empty)
  694. {
  695. formatPrefix = prefix + ":";
  696. }
  697. if (openStartElement || attributeWrittenForElement) {
  698. if (newLineOnAttributes)
  699. WriteIndent ();
  700. else
  701. w.Write (" ");
  702. }
  703. w.Write (formatPrefix);
  704. w.Write (localName);
  705. w.Write ('=');
  706. w.Write (quoteChar);
  707. openAttribute = true;
  708. attributeWrittenForElement = true;
  709. ws = WriteState.Attribute;
  710. if (prefix == "xmlns" || prefix == String.Empty && localName == "xmlns") {
  711. if (prefix != openElementPrefix || openElementNS == null)
  712. shouldAddSavedNsToManager = true;
  713. saveAttributeValue = true;
  714. savedAttributePrefix = (prefix == "xmlns") ? localName : String.Empty;
  715. savingAttributeValue = String.Empty;
  716. }
  717. }
  718. private string CheckNewPrefix (bool createPrefix, string prefix, string ns)
  719. {
  720. do {
  721. if (createPrefix)
  722. prefix = "d" + indentLevel + "p" + (++autoCreatedPrefixes);
  723. createPrefix = false;
  724. // Check if prefix exists.
  725. // If yes - check if namespace is the same.
  726. if (newAttributeNamespaces [prefix] == null)
  727. newAttributeNamespaces.Add (prefix, ns);
  728. else if (!newAttributeNamespaces [prefix].Equals (ns))
  729. createPrefix = true;
  730. } while (createPrefix);
  731. return prefix;
  732. }
  733. public override void WriteStartDocument ()
  734. {
  735. WriteStartDocument ("");
  736. }
  737. public override void WriteStartDocument (bool standalone)
  738. {
  739. string standaloneFormatting;
  740. if (standalone == true)
  741. standaloneFormatting = String.Format (" standalone={0}yes{0}", quoteChar);
  742. else
  743. standaloneFormatting = String.Format (" standalone={0}no{0}", quoteChar);
  744. WriteStartDocument (standaloneFormatting);
  745. }
  746. private void WriteStartDocument (string standaloneFormatting)
  747. {
  748. if (documentStarted == true)
  749. throw InvalidOperationError ("WriteStartDocument should be the first call.");
  750. if (hasRoot)
  751. throw XmlError ("WriteStartDocument called twice.");
  752. isDocumentEntity = true;
  753. // CheckState ();
  754. CheckOutputState ();
  755. string encodingFormatting = "";
  756. if (!nullEncoding)
  757. encodingFormatting = String.Format (" encoding={0}{1}{0}", quoteChar, w.Encoding.WebName);
  758. w.Write("<?xml version={0}1.0{0}{1}{2}?>", quoteChar, encodingFormatting, standaloneFormatting);
  759. ws = WriteState.Prolog;
  760. }
  761. public override void WriteStartElement (string prefix, string localName, string ns)
  762. {
  763. if (!Namespaces && (((prefix != null) && (prefix != String.Empty))
  764. || ((ns != null) && (ns != String.Empty))))
  765. throw ArgumentError ("Cannot set the namespace if Namespaces is 'false'.");
  766. if ((prefix != null && prefix.Length > 0) && ((ns == null)))
  767. throw ArgumentError ("Cannot use a prefix with an empty namespace.");
  768. // ignore non-namespaced node's prefix.
  769. if (ns == null || ns == String.Empty)
  770. prefix = String.Empty;
  771. WriteStartElementInternal (prefix, localName, ns);
  772. }
  773. private void WriteStartElementInternal (string prefix, string localName, string ns)
  774. {
  775. CheckState ();
  776. hasRoot = true;
  777. CloseStartElement ();
  778. newAttributeNamespaces.Clear ();
  779. userWrittenNamespaces.Clear ();
  780. shouldCheckElementXmlns = false;
  781. if (prefix == null && ns != null)
  782. prefix = namespaceManager.LookupPrefix (ns, false);
  783. if (prefix == null)
  784. prefix = String.Empty;
  785. WriteIndent ();
  786. w.Write ('<');
  787. if (prefix != String.Empty) {
  788. w.Write (prefix);
  789. w.Write (':');
  790. }
  791. w.Write (localName);
  792. if (openElements.Count == openElementCount)
  793. openElements.Add (new XmlTextWriterOpenElement (prefix, localName));
  794. else
  795. ((XmlTextWriterOpenElement) openElements [openElementCount]).Reset (prefix, localName);
  796. openElementCount++;
  797. ws = WriteState.Element;
  798. openStartElement = true;
  799. openElementNS = ns;
  800. openElementPrefix = prefix;
  801. namespaceManager.PushScope ();
  802. indentLevel++;
  803. if (ns != null) {
  804. if (ns.Length > 0) {
  805. string existing = LookupPrefix (ns);
  806. if (existing != prefix) {
  807. shouldCheckElementXmlns = true;
  808. namespaceManager.AddNamespace (prefix, ns);
  809. }
  810. } else {
  811. if (ns != namespaceManager.DefaultNamespace) {
  812. shouldCheckElementXmlns = true;
  813. namespaceManager.AddNamespace ("", ns);
  814. }
  815. }
  816. }
  817. }
  818. public override void WriteString (string text)
  819. {
  820. switch (ws) {
  821. case WriteState.Start:
  822. case WriteState.Prolog:
  823. if (isDocumentEntity)
  824. throw InvalidOperationError ("Token content in state Prolog would result in an invalid XML document.");
  825. ws = WriteState.Content;
  826. break;
  827. }
  828. WriteStringInternal (text, true);
  829. // MS.NET (1.0) saves attribute value only at WriteString.
  830. if (saveAttributeValue)
  831. // In most cases it will be called one time, so simply use string + string.
  832. savingAttributeValue += text;
  833. }
  834. string [] replacements = new string [] {
  835. "&amp;", "&lt;", "&gt;", "&quot;", "&apos;",
  836. "&#xD;", "&#xA;"};
  837. private string EscapeString (string source, bool outsideAttribute)
  838. {
  839. int start = 0;
  840. int pos = 0;
  841. int count = source.Length;
  842. char invalid = ' ';
  843. for (int i = 0; i < count; i++) {
  844. switch (source [i]) {
  845. case '&': pos = 0; break;
  846. case '<': pos = 1; break;
  847. case '>': pos = 2; break;
  848. case '\"':
  849. if (outsideAttribute) continue;
  850. if (QuoteChar == '\'') continue;
  851. pos = 3; break;
  852. case '\'':
  853. if (outsideAttribute) continue;
  854. if (QuoteChar == '\"') continue;
  855. pos = 4; break;
  856. case '\r':
  857. if (outsideAttribute)
  858. continue;
  859. pos = 5; break;
  860. case '\n':
  861. if (outsideAttribute)
  862. continue;
  863. pos = 6; break;
  864. default:
  865. if (XmlChar.IsInvalid (source [i])) {
  866. if (Char.IsSurrogate (source [i]) && source [i] < 0xDC00 &&
  867. i + 1 < count && Char.IsSurrogate (source [i + 1]) && source [i + 1] >= 0xDC00) {
  868. // A legitimate UTF-16 surrogate pair; let it through.
  869. i++;
  870. continue;
  871. } else {
  872. if (checkCharacters)
  873. throw ArgumentError (String.Format ("Character hexadecimal value {0:4x} is invalid.", (int) source [i]));
  874. invalid = source [i];
  875. pos = -1;
  876. break;
  877. }
  878. }
  879. else
  880. continue;
  881. }
  882. if (cachedStringBuilder == null)
  883. cachedStringBuilder = new StringBuilder ();
  884. cachedStringBuilder.Append (source.Substring (start, i - start));
  885. if (pos < 0) {
  886. cachedStringBuilder.Append ("&#x");
  887. // if (invalid < (char) 255)
  888. // cachedStringBuilder.Append (((int) invalid).ToString ("X02", CultureInfo.InvariantCulture));
  889. // else
  890. // cachedStringBuilder.Append (((int) invalid).ToString ("X04", CultureInfo.InvariantCulture));
  891. cachedStringBuilder.Append (((int) invalid).ToString ("X", CultureInfo.InvariantCulture));
  892. cachedStringBuilder.Append (";");
  893. }
  894. #if NET_2_0
  895. else if (outsideAttribute && pos >= 5) {
  896. cachedStringBuilder.Append (newLineChars);
  897. // all \r,\n,\r\n are replaced with
  898. // NewLineChars, so \n after \r should
  899. // be consumed here.
  900. if (pos == 5 && i + 1 < count && source [i + 1] == '\n')
  901. i++;
  902. }
  903. #endif
  904. else
  905. cachedStringBuilder.Append (replacements [pos]);
  906. start = i + 1;
  907. }
  908. if (start == 0)
  909. return source;
  910. else if (start < count)
  911. cachedStringBuilder.Append (source.Substring (start, count - start));
  912. string s = cachedStringBuilder.ToString ();
  913. cachedStringBuilder.Length = 0;
  914. return s;
  915. }
  916. private void WriteStringInternal (string text, bool entitize)
  917. {
  918. if (text == null || text.Length == 0)
  919. return;
  920. CheckState ();
  921. if (entitize)
  922. text = EscapeString (text, !openAttribute);
  923. if (!openAttribute)
  924. {
  925. IndentingOverriden = true;
  926. CloseStartElement ();
  927. }
  928. if (!openXmlLang && !openXmlSpace)
  929. w.Write (text);
  930. else
  931. {
  932. if (openXmlLang)
  933. xmlLang = text;
  934. else
  935. {
  936. switch (text)
  937. {
  938. case "default":
  939. xmlSpace = XmlSpace.Default;
  940. break;
  941. case "preserve":
  942. xmlSpace = XmlSpace.Preserve;
  943. break;
  944. default:
  945. throw ArgumentError ("'{0}' is an invalid xml:space value.");
  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 (ws == null || ws.Length == 0) {
  967. throw ArgumentError ("Only white space characters should be used.");
  968. }
  969. if (!XmlChar.IsWhitespace (ws))
  970. throw ArgumentError ("Invalid Whitespace");
  971. CheckState ();
  972. if (!openAttribute) {
  973. IndentingOverriden = true;
  974. CloseStartElement ();
  975. }
  976. w.Write (ws);
  977. }
  978. private Exception ArgumentError (string message)
  979. {
  980. #if NET_2_0
  981. ws = WriteState.Error;
  982. #endif
  983. return new ArgumentException (message);
  984. }
  985. private Exception ArgumentError (string message, string name)
  986. {
  987. #if NET_2_0
  988. ws = WriteState.Error;
  989. #endif
  990. return new ArgumentException (message);
  991. }
  992. private Exception InvalidOperationError (string message)
  993. {
  994. #if NET_2_0
  995. ws = WriteState.Error;
  996. #endif
  997. return new InvalidOperationException (message);
  998. }
  999. private Exception XmlError (string message)
  1000. {
  1001. #if NET_2_0
  1002. ws = WriteState.Error;
  1003. #endif
  1004. return new XmlException (message);
  1005. }
  1006. #endregion
  1007. }
  1008. }