XmlBinaryDictionaryWriter.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  1. //
  2. // XmlBinaryDictionaryWriter.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2005, 2007 Novell, Inc. http://www.novell.com
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Collections;
  31. using System.Collections.Specialized;
  32. using System.Collections.Generic;
  33. using System.Globalization;
  34. using System.IO;
  35. using System.Linq;
  36. using System.Text;
  37. using BF = System.Xml.XmlBinaryFormat;
  38. namespace System.Xml
  39. {
  40. internal partial class XmlBinaryDictionaryWriter : XmlDictionaryWriter
  41. {
  42. class MyBinaryWriter : BinaryWriter
  43. {
  44. public MyBinaryWriter (Stream s)
  45. : base (s)
  46. {
  47. }
  48. public void WriteFlexibleInt (int value)
  49. {
  50. Write7BitEncodedInt (value);
  51. }
  52. }
  53. #region Fields
  54. MyBinaryWriter original, writer, buffer_writer;
  55. IXmlDictionary dict_ext;
  56. XmlDictionary dict_int = new XmlDictionary ();
  57. XmlBinaryWriterSession session;
  58. bool owns_stream;
  59. Encoding utf8Enc = new UTF8Encoding ();
  60. MemoryStream buffer = new MemoryStream ();
  61. const string XmlNamespace = "http://www.w3.org/XML/1998/namespace";
  62. const string XmlnsNamespace = "http://www.w3.org/2000/xmlns/";
  63. WriteState state = WriteState.Start;
  64. bool open_start_element = false;
  65. // transient current node info
  66. List<KeyValuePair<string,object>> namespaces = new List<KeyValuePair<string,object>> ();
  67. string xml_lang = null;
  68. XmlSpace xml_space = XmlSpace.None;
  69. int ns_index = 0;
  70. // stacked info
  71. Stack<int> ns_index_stack = new Stack<int> ();
  72. Stack<string> xml_lang_stack = new Stack<string> ();
  73. Stack<XmlSpace> xml_space_stack = new Stack<XmlSpace> ();
  74. Stack<string> element_ns_stack = new Stack<string> ();
  75. string element_ns = String.Empty;
  76. int element_count;
  77. string element_prefix; // only meaningful at Element state
  78. // current attribute info
  79. string attr_value;
  80. string current_attr_prefix;
  81. object current_attr_name, current_attr_ns;
  82. bool attr_typed_value;
  83. SaveTarget save_target;
  84. enum SaveTarget {
  85. None,
  86. Namespaces,
  87. XmlLang,
  88. XmlSpace
  89. }
  90. // XmlWriterSettings support
  91. #endregion
  92. #region Constructors
  93. public XmlBinaryDictionaryWriter (Stream stream,
  94. IXmlDictionary dictionary,
  95. XmlBinaryWriterSession session, bool ownsStream)
  96. {
  97. if (dictionary == null)
  98. dictionary = new XmlDictionary ();
  99. if (session == null)
  100. session = new XmlBinaryWriterSession ();
  101. original = new MyBinaryWriter (stream);
  102. this.writer = original;
  103. buffer_writer = new MyBinaryWriter (buffer);
  104. this.dict_ext = dictionary;
  105. this.session = session;
  106. owns_stream = ownsStream;
  107. AddNamespace ("xml", "http://www.w3.org/XML/1998/namespace");
  108. AddNamespace ("xml", "http://www.w3.org/2000/xmlns/");
  109. ns_index = 2;
  110. }
  111. #endregion
  112. #region Properties
  113. public override WriteState WriteState {
  114. get { return state; }
  115. }
  116. public override string XmlLang {
  117. get { return xml_lang; }
  118. }
  119. public override XmlSpace XmlSpace {
  120. get { return xml_space; }
  121. }
  122. #endregion
  123. #region Methods
  124. private void AddMissingElementXmlns ()
  125. {
  126. // push new namespaces to manager.
  127. for (int i = ns_index; i < namespaces.Count; i++) {
  128. var ent = namespaces [i];
  129. string prefix = (string) ent.Key;
  130. string ns = ent.Value as string;
  131. XmlDictionaryString dns = ent.Value as XmlDictionaryString;
  132. if (ns != null) {
  133. if (prefix.Length > 0) {
  134. writer.Write (BF.PrefixNSString);
  135. writer.Write (prefix);
  136. }
  137. else
  138. writer.Write (BF.DefaultNSString);
  139. writer.Write (ns);
  140. } else {
  141. if (prefix.Length > 0) {
  142. writer.Write (BF.PrefixNSIndex);
  143. writer.Write (prefix);
  144. }
  145. else
  146. writer.Write (BF.DefaultNSIndex);
  147. WriteDictionaryIndex (dns);
  148. }
  149. }
  150. ns_index = namespaces.Count;
  151. }
  152. private void CheckState ()
  153. {
  154. if (state == WriteState.Closed) {
  155. throw new InvalidOperationException ("The Writer is closed.");
  156. }
  157. }
  158. void ProcessStateForContent ()
  159. {
  160. CheckState ();
  161. if (state == WriteState.Element)
  162. CloseStartElement ();
  163. ProcessPendingBuffer (false, false);
  164. if (state != WriteState.Attribute)
  165. writer = buffer_writer;
  166. }
  167. void ProcessTypedValue ()
  168. {
  169. ProcessStateForContent ();
  170. if (state == WriteState.Attribute) {
  171. if (attr_typed_value)
  172. throw new InvalidOperationException (String.Format ("A typed value for the attribute '{0}' in namespace '{1}' was already written", current_attr_name, current_attr_ns));
  173. attr_typed_value = true;
  174. }
  175. }
  176. void ProcessPendingBuffer (bool last, bool endElement)
  177. {
  178. if (buffer.Position > 0) {
  179. byte [] arr = buffer.GetBuffer ();
  180. if (endElement)
  181. arr [0]++;
  182. original.Write (arr, 0, (int) buffer.Position);
  183. buffer.SetLength (0);
  184. }
  185. if (last)
  186. writer = original;
  187. }
  188. public override void Close ()
  189. {
  190. CloseOpenAttributeAndElements ();
  191. if (owns_stream)
  192. writer.Close ();
  193. else if (state != WriteState.Closed)
  194. writer.Flush ();
  195. state = WriteState.Closed;
  196. }
  197. private void CloseOpenAttributeAndElements ()
  198. {
  199. CloseStartElement ();
  200. while (element_count > 0)
  201. WriteEndElement ();
  202. }
  203. private void CloseStartElement ()
  204. {
  205. if (!open_start_element)
  206. return;
  207. if (state == WriteState.Attribute)
  208. WriteEndAttribute ();
  209. AddMissingElementXmlns ();
  210. state = WriteState.Content;
  211. open_start_element = false;
  212. }
  213. public override void Flush ()
  214. {
  215. writer.Flush ();
  216. }
  217. public override string LookupPrefix (string ns)
  218. {
  219. if (ns == null || ns == String.Empty)
  220. throw new ArgumentException ("The Namespace cannot be empty.");
  221. var de = namespaces.LastOrDefault (i => i.Value.ToString () == ns);
  222. return de.Key; // de is KeyValuePair and its default key is null.
  223. }
  224. public override void WriteBase64 (byte[] buffer, int index, int count)
  225. {
  226. if (count < 0)
  227. throw new IndexOutOfRangeException ("Negative count");
  228. ProcessStateForContent ();
  229. if (count < 0x100) {
  230. writer.Write (BF.Bytes8);
  231. writer.Write ((byte) count);
  232. writer.Write (buffer, index, count);
  233. } else if (count < 0x10000) {
  234. writer.Write (BF.Bytes8);
  235. writer.Write ((ushort) count);
  236. writer.Write (buffer, index, count);
  237. } else {
  238. writer.Write (BF.Bytes32);
  239. writer.Write (count);
  240. writer.Write (buffer, index, count);
  241. }
  242. }
  243. public override void WriteCData (string text)
  244. {
  245. if (text.IndexOf ("]]>") >= 0)
  246. throw new ArgumentException ("CDATA section cannot contain text \"]]>\".");
  247. ProcessStateForContent ();
  248. WriteTextBinary (text);
  249. }
  250. public override void WriteCharEntity (char ch)
  251. {
  252. WriteChars (new char [] {ch}, 0, 1);
  253. }
  254. public override void WriteChars (char[] buffer, int index, int count)
  255. {
  256. ProcessStateForContent ();
  257. int blen = Encoding.UTF8.GetByteCount (buffer, index, count);
  258. if (blen == 0)
  259. writer.Write (BF.EmptyText);
  260. else if (blen < 0x100) {
  261. writer.Write (BF.Chars8);
  262. writer.Write ((byte) blen);
  263. writer.Write (buffer, index, count);
  264. } else if (blen < 0x10000) {
  265. writer.Write (BF.Chars16);
  266. writer.Write ((ushort) blen);
  267. writer.Write (buffer, index, count);
  268. } else {
  269. writer.Write (BF.Chars32);
  270. writer.Write (blen);
  271. writer.Write (buffer, index, count);
  272. }
  273. }
  274. public override void WriteComment (string text)
  275. {
  276. if (text.EndsWith("-"))
  277. throw new ArgumentException ("An XML comment cannot contain \"--\" inside.");
  278. else if (text.IndexOf("--") > 0)
  279. throw new ArgumentException ("An XML comment cannot end with \"-\".");
  280. ProcessStateForContent ();
  281. if (state == WriteState.Attribute)
  282. throw new InvalidOperationException ("Comment node is not allowed inside an attribute");
  283. writer.Write (BF.Comment);
  284. writer.Write (text);
  285. }
  286. public override void WriteDocType (string name, string pubid, string sysid, string subset)
  287. {
  288. throw new NotSupportedException ("This XmlWriter implementation does not support document type.");
  289. }
  290. public override void WriteEndAttribute ()
  291. {
  292. if (state != WriteState.Attribute)
  293. throw new InvalidOperationException("Token EndAttribute in state Start would result in an invalid XML document.");
  294. CheckState ();
  295. if (attr_value == null)
  296. attr_value = String.Empty;
  297. switch (save_target) {
  298. case SaveTarget.XmlLang:
  299. xml_lang = attr_value;
  300. goto default;
  301. case SaveTarget.XmlSpace:
  302. switch (attr_value) {
  303. case "preserve":
  304. xml_space = XmlSpace.Preserve;
  305. break;
  306. case "default":
  307. xml_space = XmlSpace.Default;
  308. break;
  309. default:
  310. throw new ArgumentException (String.Format ("Invalid xml:space value: '{0}'", attr_value));
  311. }
  312. goto default;
  313. case SaveTarget.Namespaces:
  314. if (current_attr_name.ToString ().Length > 0 && attr_value.Length == 0)
  315. throw new ArgumentException ("Cannot use prefix with an empty namespace.");
  316. AddNamespaceChecked (current_attr_name.ToString (), attr_value);
  317. break;
  318. default:
  319. if (!attr_typed_value)
  320. WriteTextBinary (attr_value);
  321. break;
  322. }
  323. if (current_attr_prefix.Length > 0 && save_target != SaveTarget.Namespaces)
  324. AddNamespaceChecked (current_attr_prefix, current_attr_ns);
  325. state = WriteState.Element;
  326. current_attr_prefix = null;
  327. current_attr_name = null;
  328. current_attr_ns = null;
  329. attr_value = null;
  330. attr_typed_value = false;
  331. }
  332. public override void WriteEndDocument ()
  333. {
  334. CloseOpenAttributeAndElements ();
  335. switch (state) {
  336. case WriteState.Start:
  337. throw new InvalidOperationException ("Document has not started.");
  338. case WriteState.Prolog:
  339. throw new ArgumentException ("This document does not have a root element.");
  340. }
  341. state = WriteState.Start;
  342. }
  343. bool SupportsCombinedEndElementSupport (byte operation)
  344. {
  345. switch (operation) {
  346. case BF.Comment:
  347. return false;
  348. }
  349. return true;
  350. }
  351. public override void WriteEndElement ()
  352. {
  353. if (element_count-- == 0)
  354. throw new InvalidOperationException("There was no XML start tag open.");
  355. if (state == WriteState.Attribute)
  356. WriteEndAttribute ();
  357. // Comment+EndElement does not exist
  358. bool needExplicitEndElement = buffer.Position == 0 || !SupportsCombinedEndElementSupport (buffer.GetBuffer () [0]);
  359. ProcessPendingBuffer (true, !needExplicitEndElement);
  360. CheckState ();
  361. AddMissingElementXmlns ();
  362. if (needExplicitEndElement)
  363. writer.Write (BF.EndElement);
  364. element_ns = element_ns_stack.Pop ();
  365. xml_lang = xml_lang_stack.Pop ();
  366. xml_space = xml_space_stack.Pop ();
  367. int cur = namespaces.Count;
  368. ns_index = ns_index_stack.Pop ();
  369. namespaces.RemoveRange (ns_index, cur - ns_index);
  370. open_start_element = false;
  371. Depth--;
  372. }
  373. public override void WriteEntityRef (string name)
  374. {
  375. throw new NotSupportedException ("This XmlWriter implementation does not support entity references.");
  376. }
  377. public override void WriteFullEndElement ()
  378. {
  379. WriteEndElement ();
  380. }
  381. public override void WriteProcessingInstruction (string name, string text)
  382. {
  383. if (name != "xml")
  384. throw new ArgumentException ("Processing instructions are not supported. ('xml' is allowed for XmlDeclaration; this is because of design problem of ECMA XmlWriter)");
  385. // Otherwise, silently ignored. WriteStartDocument()
  386. // is still callable after this method(!)
  387. }
  388. public override void WriteQualifiedName (XmlDictionaryString local, XmlDictionaryString ns)
  389. {
  390. string prefix = namespaces.LastOrDefault (i => i.Value.ToString () == ns.ToString ()).Key;
  391. bool use_dic = prefix != null;
  392. if (prefix == null)
  393. prefix = LookupPrefix (ns.Value);
  394. if (prefix == null)
  395. throw new ArgumentException (String.Format ("Namespace URI '{0}' is not bound to any of the prefixes", ns));
  396. ProcessTypedValue ();
  397. if (use_dic && prefix.Length == 1) {
  398. writer.Write (BF.QNameIndex);
  399. writer.Write ((byte) (prefix [0] - 'a'));
  400. WriteDictionaryIndex (local);
  401. } else {
  402. // QNameIndex is not applicable.
  403. WriteString (prefix);
  404. WriteString (":");
  405. WriteString (local);
  406. }
  407. }
  408. public override void WriteRaw (string data)
  409. {
  410. WriteString (data);
  411. }
  412. public override void WriteRaw (char[] buffer, int index, int count)
  413. {
  414. WriteChars (buffer, index, count);
  415. }
  416. void CheckStateForAttribute ()
  417. {
  418. CheckState ();
  419. if (state != WriteState.Element)
  420. throw new InvalidOperationException ("Token StartAttribute in state " + WriteState + " would result in an invalid XML document.");
  421. }
  422. string CreateNewPrefix ()
  423. {
  424. return CreateNewPrefix (String.Empty);
  425. }
  426. string CreateNewPrefix (string p)
  427. {
  428. for (char c = 'a'; c <= 'z'; c++)
  429. if (!namespaces.Any (iter => iter.Key == p + c))
  430. return p + c;
  431. for (char c = 'a'; c <= 'z'; c++) {
  432. var s = CreateNewPrefix (c.ToString ());
  433. if (s != null)
  434. return s;
  435. }
  436. throw new InvalidOperationException ("too many prefix population");
  437. }
  438. bool CollectionContains (ICollection col, string value)
  439. {
  440. foreach (string v in col)
  441. if (v == value)
  442. return true;
  443. return false;
  444. }
  445. void ProcessStartAttributeCommon (ref string prefix, string localName, string ns, object nameObj, object nsObj)
  446. {
  447. // dummy prefix is created here, while the caller
  448. // still uses empty string as the prefix there.
  449. if (prefix.Length == 0 && ns.Length > 0) {
  450. prefix = LookupPrefix (ns);
  451. // Not only null but also ""; when the returned
  452. // string is empty, then it still needs a dummy
  453. // prefix, since default namespace does not
  454. // apply to attribute
  455. if (String.IsNullOrEmpty (prefix))
  456. prefix = CreateNewPrefix ();
  457. }
  458. else if (prefix.Length > 0 && ns.Length == 0) {
  459. switch (prefix) {
  460. case "xml":
  461. nsObj = ns = XmlNamespace;
  462. break;
  463. case "xmlns":
  464. nsObj = ns = XmlnsNamespace;
  465. break;
  466. default:
  467. throw new ArgumentException ("Cannot use prefix with an empty namespace.");
  468. }
  469. }
  470. // here we omit such cases that it is used for writing
  471. // namespace-less xml, unlike XmlTextWriter.
  472. if (prefix == "xmlns" && ns != XmlnsNamespace)
  473. throw new ArgumentException (String.Format ("The 'xmlns' attribute is bound to the reserved namespace '{0}'", XmlnsNamespace));
  474. CheckStateForAttribute ();
  475. state = WriteState.Attribute;
  476. save_target = SaveTarget.None;
  477. switch (prefix) {
  478. case "xml":
  479. // MS.NET looks to allow other names than
  480. // lang and space (e.g. xml:link, xml:hack).
  481. ns = XmlNamespace;
  482. switch (localName) {
  483. case "lang":
  484. save_target = SaveTarget.XmlLang;
  485. break;
  486. case "space":
  487. save_target = SaveTarget.XmlSpace;
  488. break;
  489. }
  490. break;
  491. case "xmlns":
  492. save_target = SaveTarget.Namespaces;
  493. break;
  494. }
  495. current_attr_prefix = prefix;
  496. current_attr_name = nameObj;
  497. current_attr_ns = nsObj;
  498. }
  499. public override void WriteStartAttribute (string prefix, string localName, string ns)
  500. {
  501. if (prefix == null)
  502. prefix = String.Empty;
  503. if (ns == null)
  504. ns = String.Empty;
  505. if (localName == "xmlns" && prefix.Length == 0) {
  506. prefix = "xmlns";
  507. localName = String.Empty;
  508. }
  509. ProcessStartAttributeCommon (ref prefix, localName, ns, localName, ns);
  510. // for namespace nodes we don't write attribute node here.
  511. if (save_target == SaveTarget.Namespaces)
  512. return;
  513. byte op = prefix.Length == 1 && 'a' <= prefix [0] && prefix [0] <= 'z' ?
  514. (byte) (prefix [0] - 'a' + BF.PrefixNAttrStringStart) :
  515. prefix.Length == 0 ? BF.AttrString :
  516. BF.AttrStringPrefix;
  517. if (BF.PrefixNAttrStringStart <= op && op <= BF.PrefixNAttrStringEnd) {
  518. writer.Write (op);
  519. writer.Write (localName);
  520. } else {
  521. writer.Write (op);
  522. if (prefix.Length > 0)
  523. writer.Write (prefix);
  524. writer.Write (localName);
  525. }
  526. }
  527. public override void WriteStartDocument ()
  528. {
  529. WriteStartDocument (false);
  530. }
  531. public override void WriteStartDocument (bool standalone)
  532. {
  533. if (state != WriteState.Start)
  534. throw new InvalidOperationException("WriteStartDocument should be the first call.");
  535. CheckState ();
  536. // write nothing to stream.
  537. state = WriteState.Prolog;
  538. }
  539. void PrepareStartElement ()
  540. {
  541. ProcessPendingBuffer (true, false);
  542. CheckState ();
  543. CloseStartElement ();
  544. Depth++;
  545. element_ns_stack.Push (element_ns);
  546. xml_lang_stack.Push (xml_lang);
  547. xml_space_stack.Push (xml_space);
  548. ns_index_stack.Push (ns_index);
  549. }
  550. public override void WriteStartElement (string prefix, string localName, string ns)
  551. {
  552. PrepareStartElement ();
  553. if ((prefix != null && prefix != String.Empty) && ((ns == null) || (ns == String.Empty)))
  554. throw new ArgumentException ("Cannot use a prefix with an empty namespace.");
  555. if (ns == null)
  556. ns = String.Empty;
  557. if (ns == String.Empty)
  558. prefix = String.Empty;
  559. if (prefix == null)
  560. prefix = String.Empty;
  561. byte op = prefix.Length == 1 && 'a' <= prefix [0] && prefix [0] <= 'z' ?
  562. (byte) (prefix [0] - 'a' + BF.PrefixNElemStringStart) :
  563. prefix.Length == 0 ? BF.ElemString :
  564. BF.ElemStringPrefix;
  565. if (BF.PrefixNElemStringStart <= op && op <= BF.PrefixNElemStringEnd) {
  566. writer.Write (op);
  567. writer.Write (localName);
  568. } else {
  569. writer.Write (op);
  570. if (prefix.Length > 0)
  571. writer.Write (prefix);
  572. writer.Write (localName);
  573. }
  574. OpenElement (prefix, ns);
  575. }
  576. void OpenElement (string prefix, object nsobj)
  577. {
  578. string ns = nsobj.ToString ();
  579. state = WriteState.Element;
  580. open_start_element = true;
  581. element_prefix = prefix;
  582. element_count++;
  583. element_ns = nsobj.ToString ();
  584. if (element_ns != String.Empty && LookupPrefix (element_ns) != prefix)
  585. AddNamespace (prefix, nsobj);
  586. }
  587. void AddNamespace (string prefix, object nsobj)
  588. {
  589. namespaces.Add (new KeyValuePair<string,object> (prefix, nsobj));
  590. }
  591. void CheckIfTextAllowed ()
  592. {
  593. switch (state) {
  594. case WriteState.Start:
  595. case WriteState.Prolog:
  596. throw new InvalidOperationException ("Token content in state Prolog would result in an invalid XML document.");
  597. }
  598. }
  599. public override void WriteString (string text)
  600. {
  601. if (text == null)
  602. throw new ArgumentNullException ("text");
  603. CheckIfTextAllowed ();
  604. if (text == null)
  605. text = String.Empty;
  606. ProcessStateForContent ();
  607. if (state == WriteState.Attribute)
  608. attr_value += text;
  609. else
  610. WriteTextBinary (text);
  611. }
  612. public override void WriteString (XmlDictionaryString text)
  613. {
  614. if (text == null)
  615. throw new ArgumentNullException ("text");
  616. CheckIfTextAllowed ();
  617. if (text == null)
  618. text = XmlDictionaryString.Empty;
  619. ProcessStateForContent ();
  620. if (state == WriteState.Attribute)
  621. attr_value += text.Value;
  622. else if (text.Equals (XmlDictionary.Empty))
  623. writer.Write (BF.EmptyText);
  624. else {
  625. writer.Write (BF.TextIndex);
  626. WriteDictionaryIndex (text);
  627. }
  628. }
  629. public override void WriteSurrogateCharEntity (char lowChar, char highChar)
  630. {
  631. WriteChars (new char [] {highChar, lowChar}, 0, 2);
  632. }
  633. public override void WriteWhitespace (string ws)
  634. {
  635. for (int i = 0; i < ws.Length; i++) {
  636. switch (ws [i]) {
  637. case ' ': case '\t': case '\r': case '\n':
  638. continue;
  639. default:
  640. throw new ArgumentException ("Invalid Whitespace");
  641. }
  642. }
  643. ProcessStateForContent ();
  644. WriteTextBinary (ws);
  645. }
  646. public override void WriteXmlnsAttribute (string prefix, string namespaceUri)
  647. {
  648. if (namespaceUri == null)
  649. throw new ArgumentNullException ("namespaceUri");
  650. if (String.IsNullOrEmpty (prefix))
  651. prefix = CreateNewPrefix ();
  652. CheckStateForAttribute ();
  653. AddNamespaceChecked (prefix, namespaceUri);
  654. state = WriteState.Element;
  655. }
  656. void AddNamespaceChecked (string prefix, object ns)
  657. {
  658. switch (ns.ToString ()) {
  659. case XmlnsNamespace:
  660. case XmlNamespace:
  661. return;
  662. }
  663. if (prefix == null)
  664. throw new InvalidOperationException ();
  665. var o = namespaces.LastOrDefault (i => i.Key == prefix);
  666. if (o.Key != null) { // i.e. exists
  667. if (o.Value.ToString () != ns.ToString ()) {
  668. if (namespaces.LastIndexOf (o) >= ns_index)
  669. throw new ArgumentException (String.Format ("The prefix '{0}' is already mapped to another namespace URI '{1}' in this element scope and cannot be mapped to '{2}'", prefix ?? "(null)", o.Value ?? "(null)", ns.ToString ()));
  670. else
  671. AddNamespace (prefix, ns);
  672. }
  673. }
  674. else
  675. AddNamespace (prefix, ns);
  676. }
  677. #region DictionaryString
  678. void WriteDictionaryIndex (XmlDictionaryString ds)
  679. {
  680. XmlDictionaryString ds2;
  681. bool isSession = false;
  682. int idx = ds.Key;
  683. if (ds.Dictionary != dict_ext) {
  684. isSession = true;
  685. if (dict_int.TryLookup (ds.Value, out ds2))
  686. ds = ds2;
  687. if (!session.TryLookup (ds, out idx))
  688. session.TryAdd (dict_int.Add (ds.Value), out idx);
  689. }
  690. if (idx >= 0x80) {
  691. writer.Write ((byte) (0x80 + ((idx % 0x80) << 1) + (isSession ? 1 : 0)));
  692. writer.Write ((byte) ((byte) (idx / 0x80) << 1));
  693. }
  694. else
  695. writer.Write ((byte) (((idx % 0x80) << 1) + (isSession ? 1 : 0)));
  696. }
  697. public override void WriteStartElement (string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
  698. {
  699. PrepareStartElement ();
  700. if (prefix == null)
  701. prefix = String.Empty;
  702. byte op = prefix.Length == 1 && 'a' <= prefix [0] && prefix [0] <= 'z' ?
  703. (byte) (prefix [0] - 'a' + BF.PrefixNElemIndexStart) :
  704. prefix.Length == 0 ? BF.ElemIndex :
  705. BF.ElemIndexPrefix;
  706. if (BF.PrefixNElemIndexStart <= op && op <= BF.PrefixNElemIndexEnd) {
  707. writer.Write (op);
  708. WriteDictionaryIndex (localName);
  709. } else {
  710. writer.Write (op);
  711. if (prefix.Length > 0)
  712. writer.Write (prefix);
  713. WriteDictionaryIndex (localName);
  714. }
  715. OpenElement (prefix, namespaceUri);
  716. }
  717. public override void WriteStartAttribute (string prefix, XmlDictionaryString localName, XmlDictionaryString ns)
  718. {
  719. if (localName == null)
  720. throw new ArgumentNullException ("localName");
  721. if (prefix == null)
  722. prefix = String.Empty;
  723. if (ns == null)
  724. ns = XmlDictionaryString.Empty;
  725. if (localName.Value == "xmlns" && prefix.Length == 0) {
  726. prefix = "xmlns";
  727. localName = XmlDictionaryString.Empty;
  728. }
  729. ProcessStartAttributeCommon (ref prefix, localName.Value, ns.Value, localName, ns);
  730. if (save_target == SaveTarget.Namespaces)
  731. return;
  732. if (prefix.Length == 1 && 'a' <= prefix [0] && prefix [0] <= 'z') {
  733. writer.Write ((byte) (prefix [0] - 'a' + BF.PrefixNAttrIndexStart));
  734. WriteDictionaryIndex (localName);
  735. } else {
  736. byte op = ns.Value.Length == 0 ? BF.AttrIndex :BF.AttrIndexPrefix;
  737. // Write to Stream
  738. writer.Write (op);
  739. if (prefix.Length > 0)
  740. writer.Write (prefix);
  741. WriteDictionaryIndex (localName);
  742. }
  743. }
  744. public override void WriteXmlnsAttribute (string prefix, XmlDictionaryString namespaceUri)
  745. {
  746. if (namespaceUri == null)
  747. throw new ArgumentNullException ("namespaceUri");
  748. if (String.IsNullOrEmpty (prefix))
  749. prefix = CreateNewPrefix ();
  750. CheckStateForAttribute ();
  751. AddNamespaceChecked (prefix, namespaceUri);
  752. state = WriteState.Element;
  753. }
  754. #endregion
  755. #region WriteValue
  756. public override void WriteValue (bool value)
  757. {
  758. ProcessTypedValue ();
  759. writer.Write ((byte) (value ? BF.BoolTrue : BF.BoolFalse));
  760. }
  761. public override void WriteValue (int value)
  762. {
  763. WriteValue ((long) value);
  764. }
  765. public override void WriteValue (long value)
  766. {
  767. ProcessTypedValue ();
  768. if (value == 0)
  769. writer.Write (BF.Zero);
  770. else if (value == 1)
  771. writer.Write (BF.One);
  772. else if (value < 0 || value > uint.MaxValue) {
  773. writer.Write (BF.Int64);
  774. for (int i = 0; i < 8; i++) {
  775. writer.Write ((byte) (value & 0xFF));
  776. value >>= 8;
  777. }
  778. } else if (value <= byte.MaxValue) {
  779. writer.Write (BF.Int8);
  780. writer.Write ((byte) value);
  781. } else if (value <= short.MaxValue) {
  782. writer.Write (BF.Int16);
  783. writer.Write ((byte) (value & 0xFF));
  784. writer.Write ((byte) (value >> 8));
  785. } else if (value <= int.MaxValue) {
  786. writer.Write (BF.Int32);
  787. for (int i = 0; i < 4; i++) {
  788. writer.Write ((byte) (value & 0xFF));
  789. value >>= 8;
  790. }
  791. }
  792. }
  793. public override void WriteValue (float value)
  794. {
  795. ProcessTypedValue ();
  796. writer.Write (BF.Single);
  797. WriteValueContent (value);
  798. }
  799. void WriteValueContent (float value)
  800. {
  801. writer.Write (value);
  802. }
  803. public override void WriteValue (double value)
  804. {
  805. ProcessTypedValue ();
  806. writer.Write (BF.Double);
  807. WriteValueContent (value);
  808. }
  809. void WriteValueContent (double value)
  810. {
  811. writer.Write (value);
  812. }
  813. public override void WriteValue (decimal value)
  814. {
  815. ProcessTypedValue ();
  816. writer.Write (BF.Decimal);
  817. WriteValueContent (value);
  818. }
  819. void WriteValueContent (decimal value)
  820. {
  821. int [] bits = Decimal.GetBits (value);
  822. // so, looks like it is saved as its internal form,
  823. // not the returned order.
  824. // BinaryWriter.Write(Decimal) is useless here.
  825. writer.Write (bits [3]);
  826. writer.Write (bits [2]);
  827. writer.Write (bits [0]);
  828. writer.Write (bits [1]);
  829. }
  830. public override void WriteValue (DateTime value)
  831. {
  832. ProcessTypedValue ();
  833. writer.Write (BF.DateTime);
  834. WriteValueContent (value);
  835. }
  836. void WriteValueContent (DateTime value)
  837. {
  838. writer.Write (value.Ticks);
  839. }
  840. public override void WriteValue (Guid value)
  841. {
  842. ProcessTypedValue ();
  843. writer.Write (BF.Guid);
  844. WriteValueContent (value);
  845. }
  846. void WriteValueContent (Guid value)
  847. {
  848. byte [] bytes = value.ToByteArray ();
  849. writer.Write (bytes, 0, bytes.Length);
  850. }
  851. public override void WriteValue (UniqueId value)
  852. {
  853. if (value == null)
  854. throw new ArgumentNullException ("value");
  855. Guid guid;
  856. if (value.TryGetGuid (out guid)) {
  857. // this conditional branching is required for
  858. // attr_typed_value not being true.
  859. ProcessTypedValue ();
  860. writer.Write (BF.UniqueId);
  861. byte [] bytes = guid.ToByteArray ();
  862. writer.Write (bytes, 0, bytes.Length);
  863. } else {
  864. WriteValue (value.ToString ());
  865. }
  866. }
  867. public override void WriteValue (TimeSpan value)
  868. {
  869. ProcessTypedValue ();
  870. writer.Write (BF.TimeSpan);
  871. WriteValueContent (value);
  872. }
  873. void WriteValueContent (TimeSpan value)
  874. {
  875. WriteBigEndian (value.Ticks, 8);
  876. }
  877. #endregion
  878. private void WriteBigEndian (long value, int digits)
  879. {
  880. long v = 0;
  881. for (int i = 0; i < digits; i++) {
  882. v = (v << 8) + (value & 0xFF);
  883. value >>= 8;
  884. }
  885. for (int i = 0; i < digits; i++) {
  886. writer.Write ((byte) (v & 0xFF));
  887. v >>= 8;
  888. }
  889. }
  890. private void WriteTextBinary (string text)
  891. {
  892. if (text.Length == 0)
  893. writer.Write (BF.EmptyText);
  894. else {
  895. char [] arr = text.ToCharArray ();
  896. WriteChars (arr, 0, arr.Length);
  897. }
  898. }
  899. #endregion
  900. #region Write typed array content
  901. // they are packed in WriteValue(), so we cannot reuse
  902. // them for array content.
  903. void WriteValueContent (bool value)
  904. {
  905. writer.Write (value ? (byte) 1 : (byte) 0);
  906. }
  907. void WriteValueContent (short value)
  908. {
  909. writer.Write (value);
  910. }
  911. void WriteValueContent (int value)
  912. {
  913. writer.Write (value);
  914. }
  915. void WriteValueContent (long value)
  916. {
  917. writer.Write (value);
  918. }
  919. #endregion
  920. }
  921. }