XmlConvert.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. //
  2. // System.Xml.XmlConvert
  3. //
  4. // Authors:
  5. // Dwivedi, Ajay kumar ([email protected])
  6. // Gonzalo Paniagua Javier ([email protected])
  7. // Alan Tam Siu Lung ([email protected])
  8. // Atsushi Enomoto ([email protected])
  9. //
  10. // (C) 2002 Ximian, Inc (http://www.ximian.com)
  11. //
  12. //
  13. // Permission is hereby granted, free of charge, to any person obtaining
  14. // a copy of this software and associated documentation files (the
  15. // "Software"), to deal in the Software without restriction, including
  16. // without limitation the rights to use, copy, modify, merge, publish,
  17. // distribute, sublicense, and/or sell copies of the Software, and to
  18. // permit persons to whom the Software is furnished to do so, subject to
  19. // the following conditions:
  20. //
  21. // The above copyright notice and this permission notice shall be
  22. // included in all copies or substantial portions of the Software.
  23. //
  24. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  28. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  29. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. //
  32. using System;
  33. using System.IO;
  34. using System.Text;
  35. using System.Globalization;
  36. using System.Xml.Schema;
  37. namespace System.Xml {
  38. public class XmlConvert {
  39. const string encodedColon = "_x003A_";
  40. const NumberStyles floatStyle = NumberStyles.AllowCurrencySymbol |
  41. NumberStyles.AllowExponent |
  42. NumberStyles.AllowDecimalPoint |
  43. NumberStyles.AllowLeadingSign;
  44. static readonly string [] datetimeFormats = {
  45. // dateTime
  46. "yyyy-MM-ddTHH:mm:ss",
  47. "yyyy-MM-ddTHH:mm:ss.f",
  48. "yyyy-MM-ddTHH:mm:ss.ff",
  49. "yyyy-MM-ddTHH:mm:ss.fff",
  50. "yyyy-MM-ddTHH:mm:ss.ffff",
  51. "yyyy-MM-ddTHH:mm:ss.fffff",
  52. "yyyy-MM-ddTHH:mm:ss.ffffff",
  53. "yyyy-MM-ddTHH:mm:ss.fffffff",
  54. "yyyy-MM-ddTHH:mm:sszzz",
  55. "yyyy-MM-ddTHH:mm:ss.fzzz",
  56. "yyyy-MM-ddTHH:mm:ss.ffzzz",
  57. "yyyy-MM-ddTHH:mm:ss.fffzzz",
  58. "yyyy-MM-ddTHH:mm:ss.ffffzzz",
  59. "yyyy-MM-ddTHH:mm:ss.fffffzzz",
  60. "yyyy-MM-ddTHH:mm:ss.ffffffzzz",
  61. "yyyy-MM-ddTHH:mm:ss.fffffffzzz",
  62. "yyyy-MM-ddTHH:mm:ssZ",
  63. "yyyy-MM-ddTHH:mm:ss.fZ",
  64. "yyyy-MM-ddTHH:mm:ss.ffZ",
  65. "yyyy-MM-ddTHH:mm:ss.fffZ",
  66. "yyyy-MM-ddTHH:mm:ss.ffffZ",
  67. "yyyy-MM-ddTHH:mm:ss.fffffZ",
  68. "yyyy-MM-ddTHH:mm:ss.ffffffZ",
  69. "yyyy-MM-ddTHH:mm:ss.fffffffZ",
  70. // time
  71. "HH:mm:ss",
  72. "HH:mm:ss.f",
  73. "HH:mm:ss.ff",
  74. "HH:mm:ss.fff",
  75. "HH:mm:ss.ffff",
  76. "HH:mm:ss.fffff",
  77. "HH:mm:ss.ffffff",
  78. "HH:mm:ss.fffffff",
  79. "HH:mm:sszzz",
  80. "HH:mm:ss.fzzz",
  81. "HH:mm:ss.ffzzz",
  82. "HH:mm:ss.fffzzz",
  83. "HH:mm:ss.ffffzzz",
  84. "HH:mm:ss.fffffzzz",
  85. "HH:mm:ss.ffffffzzz",
  86. "HH:mm:ss.fffffffzzz",
  87. "HH:mm:ssZ",
  88. "HH:mm:ss.fZ",
  89. "HH:mm:ss.ffZ",
  90. "HH:mm:ss.fffZ",
  91. "HH:mm:ss.ffffZ",
  92. "HH:mm:ss.fffffZ",
  93. "HH:mm:ss.ffffffZ",
  94. "HH:mm:ss.fffffffZ",
  95. // date
  96. "yyyy-MM-dd",
  97. "yyyy-MM-ddzzz",
  98. "yyyy-MM-ddZ",
  99. // gYearMonth
  100. "yyyy-MM",
  101. "yyyy-MMzzz",
  102. "yyyy-MMZ",
  103. // gYear
  104. "yyyy",
  105. "yyyyzzz",
  106. "yyyyZ",
  107. // gMonthDay
  108. "--MM-dd",
  109. "--MM-ddzzz",
  110. "--MM-ddZ",
  111. // gDay
  112. "---dd",
  113. "---ddzzz",
  114. "---ddZ",
  115. };
  116. public XmlConvert()
  117. {}
  118. private static string TryDecoding (string s)
  119. {
  120. if (s == null || s.Length < 6)
  121. return s;
  122. char c = '\uFFFF';
  123. try {
  124. c = (char) Int32.Parse (s.Substring (1, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
  125. } catch {
  126. return s [0] + DecodeName (s.Substring (1));
  127. }
  128. if (s.Length == 6)
  129. return c.ToString ();
  130. return c + DecodeName (s.Substring (6));
  131. }
  132. public static string DecodeName (string name)
  133. {
  134. if (name == null || name.Length == 0)
  135. return name;
  136. int pos = name.IndexOf ('_');
  137. if (pos == -1 || pos + 6 >= name.Length)
  138. return name;
  139. if ((name [pos + 1] != 'X' && name [pos + 1] != 'x') || name [pos + 6] != '_')
  140. return name [0] + DecodeName (name.Substring (1));
  141. return name.Substring (0, pos) + TryDecoding (name.Substring (pos + 1));
  142. }
  143. public static string EncodeLocalName (string name)
  144. {
  145. string encoded = EncodeName (name);
  146. int pos = encoded.IndexOf (':');
  147. if (pos == -1)
  148. return encoded;
  149. return encoded.Replace (":", encodedColon);
  150. }
  151. internal static bool IsInvalid (char c, bool firstOnlyLetter)
  152. {
  153. if (c == ':') // Special case. allowed in EncodeName, but encoded in EncodeLocalName
  154. return false;
  155. if (firstOnlyLetter)
  156. return !XmlChar.IsFirstNameChar (c);
  157. else
  158. return !XmlChar.IsNameChar (c);
  159. }
  160. private static string EncodeName (string name, bool nmtoken)
  161. {
  162. StringBuilder sb = new StringBuilder ();
  163. int length = name.Length;
  164. for (int i = 0; i < length; i++) {
  165. char c = name [i];
  166. if (IsInvalid (c, i == 0 && !nmtoken))
  167. sb.AppendFormat ("_x{0:X4}_", (int) c);
  168. else if (c == '_' && i + 6 < length && name [i+1] == 'x' && name [i + 6] == '_')
  169. sb.Append ("_x005F_");
  170. else
  171. sb.Append (c);
  172. }
  173. return sb.ToString ();
  174. }
  175. public static string EncodeName (string name)
  176. {
  177. return EncodeName (name, false);
  178. }
  179. public static string EncodeNmToken(string name)
  180. {
  181. return EncodeName (name, true);
  182. }
  183. // {true, false, 1, 0}
  184. public static bool ToBoolean(string s)
  185. {
  186. s = s.Trim (XmlChar.WhitespaceChars);
  187. switch(s)
  188. {
  189. case "1":
  190. return true;
  191. case "true":
  192. return true;
  193. case "0":
  194. return false;
  195. case "false":
  196. return false;
  197. default:
  198. throw new FormatException(s + " is not a valid boolean value");
  199. }
  200. }
  201. // LAMESPEC: It has been documented as public, but is marked as internal.
  202. internal static string ToBinHexString (byte [] buffer)
  203. {
  204. StringWriter w = new StringWriter ();
  205. WriteBinHex (buffer, 0, buffer.Length, w);
  206. return w.ToString ();
  207. }
  208. internal static void WriteBinHex (byte [] buffer, int index, int count, TextWriter w)
  209. {
  210. if (buffer == null)
  211. throw new ArgumentNullException ("buffer");
  212. if (index < 0)
  213. throw new ArgumentOutOfRangeException ("index", index, "index must be non negative integer.");
  214. if (count < 0)
  215. throw new ArgumentOutOfRangeException ("count", count, "count must be non negative integer.");
  216. if (buffer.Length < index + count)
  217. throw new ArgumentOutOfRangeException ("index and count must be smaller than the length of the buffer.");
  218. // Copied from XmlTextWriter.WriteBinHex ()
  219. int end = index + count;
  220. for (int i = index; i < end; i++) {
  221. int val = buffer [i];
  222. int high = val >> 4;
  223. int low = val & 15;
  224. if (high > 9)
  225. w.Write ((char) (high + 55));
  226. else
  227. w.Write ((char) (high + 0x30));
  228. if (low > 9)
  229. w.Write ((char) (low + 55));
  230. else
  231. w.Write ((char) (low + 0x30));
  232. }
  233. }
  234. public static byte ToByte(string s)
  235. {
  236. return Byte.Parse(s, CultureInfo.InvariantCulture);
  237. }
  238. public static char ToChar(string s)
  239. {
  240. return Char.Parse(s);
  241. }
  242. public static DateTime ToDateTime(string s)
  243. {
  244. return ToDateTime(s, datetimeFormats);
  245. }
  246. public static DateTime ToDateTime(string s, string format)
  247. {
  248. DateTimeFormatInfo d = new DateTimeFormatInfo();
  249. d.FullDateTimePattern = format;
  250. return DateTime.Parse(s, d);
  251. }
  252. public static DateTime ToDateTime(string s, string[] formats)
  253. {
  254. DateTimeStyles style = DateTimeStyles.AllowLeadingWhite |
  255. DateTimeStyles.AllowTrailingWhite;
  256. return DateTime.ParseExact (s, formats, DateTimeFormatInfo.InvariantInfo, style);
  257. }
  258. public static Decimal ToDecimal(string s)
  259. {
  260. return Decimal.Parse(s, CultureInfo.InvariantCulture);
  261. }
  262. public static double ToDouble(string s)
  263. {
  264. if (s == null)
  265. throw new ArgumentNullException();
  266. if (s == "INF")
  267. return Double.PositiveInfinity;
  268. if (s == "-INF")
  269. return Double.NegativeInfinity;
  270. if (s == "NaN")
  271. return Double.NaN;
  272. return Double.Parse (s, floatStyle, CultureInfo.InvariantCulture);
  273. }
  274. public static Guid ToGuid(string s)
  275. {
  276. return new Guid(s);
  277. }
  278. public static short ToInt16(string s)
  279. {
  280. return Int16.Parse(s, CultureInfo.InvariantCulture);
  281. }
  282. public static int ToInt32(string s)
  283. {
  284. return Int32.Parse(s, CultureInfo.InvariantCulture);
  285. }
  286. public static long ToInt64(string s)
  287. {
  288. return Int64.Parse(s, CultureInfo.InvariantCulture);
  289. }
  290. [CLSCompliant (false)]
  291. public static SByte ToSByte(string s)
  292. {
  293. return SByte.Parse(s, CultureInfo.InvariantCulture);
  294. }
  295. public static float ToSingle(string s)
  296. {
  297. if (s == null)
  298. throw new ArgumentNullException();
  299. if (s == "INF")
  300. return Single.PositiveInfinity;
  301. if (s == "-INF")
  302. return Single.NegativeInfinity;
  303. if (s == "NaN")
  304. return Single.NaN;
  305. return Single.Parse(s, floatStyle, CultureInfo.InvariantCulture);
  306. }
  307. public static string ToString(Guid value)
  308. {
  309. return value.ToString("D", CultureInfo.InvariantCulture);
  310. }
  311. public static string ToString(int value)
  312. {
  313. return value.ToString(CultureInfo.InvariantCulture);
  314. }
  315. public static string ToString(short value)
  316. {
  317. return value.ToString(CultureInfo.InvariantCulture);
  318. }
  319. public static string ToString(byte value)
  320. {
  321. return value.ToString(CultureInfo.InvariantCulture);
  322. }
  323. public static string ToString(long value)
  324. {
  325. return value.ToString(CultureInfo.InvariantCulture);
  326. }
  327. public static string ToString(char value)
  328. {
  329. return value.ToString(CultureInfo.InvariantCulture);
  330. }
  331. public static string ToString(bool value)
  332. {
  333. if (value) return "true";
  334. return "false";
  335. }
  336. [CLSCompliant (false)]
  337. public static string ToString(SByte value)
  338. {
  339. return value.ToString(CultureInfo.InvariantCulture);
  340. }
  341. public static string ToString(Decimal value)
  342. {
  343. return value.ToString (CultureInfo.InvariantCulture);
  344. }
  345. [CLSCompliant (false)]
  346. public static string ToString(UInt64 value)
  347. {
  348. return value.ToString(CultureInfo.InvariantCulture);
  349. }
  350. public static string ToString (TimeSpan value)
  351. {
  352. StringBuilder builder = new StringBuilder ();
  353. if (value.Ticks < 0) {
  354. builder.Append ('-');
  355. value = value.Negate ();
  356. }
  357. builder.Append ('P');
  358. if (value.Days > 0)
  359. builder.Append (value.Days).Append ('D');
  360. if (value.Days > 0 || value.Hours > 0 || value.Minutes > 0 || value.Seconds > 0 || value.Milliseconds > 0) {
  361. builder.Append('T');
  362. if (value.Hours > 0)
  363. builder.Append (value.Hours).Append ('H');
  364. if (value.Minutes > 0)
  365. builder.Append (value.Minutes).Append ('M');
  366. if (value.Seconds > 0 || value.Milliseconds > 0) {
  367. builder.Append (value.Seconds);
  368. if (value.Milliseconds > 0)
  369. builder.Append ('.').AppendFormat ("{0:000}", value.Milliseconds);
  370. builder.Append ('S');
  371. }
  372. }
  373. return builder.ToString ();
  374. }
  375. public static string ToString(double value)
  376. {
  377. if (Double.IsNegativeInfinity(value)) return "-INF";
  378. if (Double.IsPositiveInfinity(value)) return "INF";
  379. if (Double.IsNaN(value)) return "NaN";
  380. return value.ToString(CultureInfo.InvariantCulture);
  381. }
  382. public static string ToString(float value)
  383. {
  384. if (Single.IsNegativeInfinity(value)) return "-INF";
  385. if (Single.IsPositiveInfinity(value)) return "INF";
  386. if (Single.IsNaN(value)) return "NaN";
  387. return value.ToString(CultureInfo.InvariantCulture);
  388. }
  389. [CLSCompliant (false)]
  390. public static string ToString(UInt32 value)
  391. {
  392. return value.ToString(CultureInfo.InvariantCulture);
  393. }
  394. [CLSCompliant (false)]
  395. public static string ToString(UInt16 value)
  396. {
  397. return value.ToString(CultureInfo.InvariantCulture);
  398. }
  399. public static string ToString(DateTime value)
  400. {
  401. return value.ToString("yyyy-MM-ddTHH:mm:ss.fffffffzzz", CultureInfo.InvariantCulture);
  402. }
  403. public static string ToString(DateTime value, string format)
  404. {
  405. return value.ToString(format, CultureInfo.InvariantCulture);
  406. }
  407. public static TimeSpan ToTimeSpan(string s)
  408. {
  409. if (s.Length == 0)
  410. throw new ArgumentException ("Invalid format string for duration schema datatype.");
  411. int start = 0;
  412. if (s [0] == '-')
  413. start = 1;
  414. bool minusValue = (start == 1);
  415. if (s [start] != 'P')
  416. throw new ArgumentException ("Invalid format string for duration schema datatype.");
  417. start++;
  418. int parseStep = 0;
  419. int days = 0;
  420. bool isTime = false;
  421. int hours = 0;
  422. int minutes = 0;
  423. int seconds = 0;
  424. bool error = false;
  425. int i = start;
  426. while (i < s.Length) {
  427. if (s [i] == 'T') {
  428. isTime = true;
  429. parseStep = 4;
  430. i++;
  431. start = i;
  432. continue;
  433. }
  434. for (; i < s.Length; i++) {
  435. if (!Char.IsDigit (s [i]))
  436. break;
  437. }
  438. int value = int.Parse (s.Substring (start, i - start), CultureInfo.InvariantCulture);
  439. switch (s [i]) {
  440. case 'Y':
  441. days += value * 365;
  442. if (parseStep > 0)
  443. error = true;
  444. else
  445. parseStep = 1;
  446. break;
  447. case 'M':
  448. if (parseStep < 2) {
  449. days += 365 * (value / 12) + 30 * (value % 12);
  450. parseStep = 2;
  451. } else if (isTime && parseStep < 6) {
  452. minutes = value;
  453. parseStep = 6;
  454. }
  455. else
  456. error = true;
  457. break;
  458. case 'D':
  459. days += value;
  460. if (parseStep > 2)
  461. error = true;
  462. else
  463. parseStep = 3;
  464. break;
  465. case 'H':
  466. hours = value;
  467. if (!isTime || parseStep > 4)
  468. error = true;
  469. else
  470. parseStep = 5;
  471. break;
  472. case 'S':
  473. seconds = value;
  474. if (!isTime || parseStep > 6)
  475. error = true;
  476. else
  477. parseStep = 7;
  478. break;
  479. default:
  480. error = true;
  481. break;
  482. }
  483. if (error)
  484. break;
  485. ++i;
  486. start = i;
  487. }
  488. if (error)
  489. throw new ArgumentException ("Invalid format string for duration schema datatype.");
  490. TimeSpan ts = new TimeSpan (days, hours, minutes, seconds);
  491. return minusValue ? -ts : ts;
  492. }
  493. [CLSCompliant (false)]
  494. public static UInt16 ToUInt16(string s)
  495. {
  496. return UInt16.Parse(s, CultureInfo.InvariantCulture);
  497. }
  498. [CLSCompliant (false)]
  499. public static UInt32 ToUInt32(string s)
  500. {
  501. return UInt32.Parse(s, CultureInfo.InvariantCulture);
  502. }
  503. [CLSCompliant (false)]
  504. public static UInt64 ToUInt64(string s)
  505. {
  506. return UInt64.Parse(s, CultureInfo.InvariantCulture);
  507. }
  508. public static string VerifyName (string name)
  509. {
  510. if (name == null)
  511. throw new ArgumentNullException("name");
  512. if (!XmlChar.IsName (name))
  513. throw new XmlException("'" + name + "' is not a valid XML Name");
  514. return name;
  515. }
  516. public static string VerifyNCName (string ncname)
  517. {
  518. if (ncname == null)
  519. throw new ArgumentNullException("ncname");
  520. if (!XmlChar.IsNCName (ncname))
  521. throw new XmlException ("'" + ncname + "' is not a valid XML NCName");
  522. return ncname;
  523. }
  524. #if NET_2_0
  525. public static string VerifyNMTOKEN (string name)
  526. #else
  527. internal static string VerifyNMTOKEN (string name)
  528. #endif
  529. {
  530. if (name == null)
  531. throw new ArgumentNullException("name");
  532. if (!XmlChar.IsNmToken (name))
  533. throw new XmlException("'" + name + "' is not a valid XML NMTOKEN");
  534. return name;
  535. }
  536. // It is documented as public method, but in fact it is not.
  537. internal static byte [] FromBinHexString (string s)
  538. {
  539. char [] chars = s.ToCharArray ();
  540. byte [] bytes = new byte [chars.Length / 2 + chars.Length % 2];
  541. FromBinHexString (chars, 0, chars.Length, bytes);
  542. return bytes;
  543. }
  544. internal static int FromBinHexString (char [] chars, int offset, int charLength, byte [] buffer)
  545. {
  546. int bufIndex = offset;
  547. for (int i = 0; i < charLength - 1; i += 2) {
  548. buffer [bufIndex] = (chars [i] > '9' ?
  549. (byte) (chars [i] - 'A' + 10) :
  550. (byte) (chars [i] - '0'));
  551. buffer [bufIndex] <<= 4;
  552. buffer [bufIndex] += chars [i + 1] > '9' ?
  553. (byte) (chars [i + 1] - 'A' + 10) :
  554. (byte) (chars [i + 1] - '0');
  555. bufIndex++;
  556. }
  557. if (charLength %2 != 0)
  558. buffer [bufIndex++] = (byte)
  559. ((chars [charLength - 1] > '9' ?
  560. (byte) (chars [charLength - 1] - 'A' + 10) :
  561. (byte) (chars [charLength - 1] - '0'))
  562. << 4);
  563. return bufIndex - offset;
  564. }
  565. }
  566. }