XmlConvert.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  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. NumberStyles.AllowLeadingWhite |
  45. NumberStyles.AllowTrailingWhite;
  46. const NumberStyles integerStyle = NumberStyles.Integer |
  47. NumberStyles.AllowLeadingWhite |
  48. NumberStyles.AllowTrailingWhite;
  49. static readonly string [] datetimeFormats = {
  50. // dateTime
  51. #if NET_2_0
  52. "yyyy-MM-ddTHH:mm:sszzz",
  53. "yyyy-MM-ddTHH:mm:ss.FFFFFFFzzz",
  54. "yyyy-MM-ddTHH:mm:ssZ",
  55. "yyyy-MM-ddTHH:mm:ss.FFFFFFFZ",
  56. "yyyy-MM-ddTHH:mm:ss",
  57. "yyyy-MM-ddTHH:mm:ss.FFFFFFF",
  58. "HH:mm:ss",
  59. "HH:mm:ss.FFFFFFF",
  60. "HH:mm:sszzz",
  61. "HH:mm:ss.FFFFFFFzzz",
  62. "HH:mm:ssZ",
  63. "HH:mm:ss.FFFFFFFZ",
  64. #else // it is not required in trunk but should make it easy to backport...
  65. "yyyy-MM-ddTHH:mm:sszzz",
  66. "yyyy-MM-ddTHH:mm:ss.fzzz",
  67. "yyyy-MM-ddTHH:mm:ss.ffzzz",
  68. "yyyy-MM-ddTHH:mm:ss.fffzzz",
  69. "yyyy-MM-ddTHH:mm:ss.ffffzzz",
  70. "yyyy-MM-ddTHH:mm:ss.fffffzzz",
  71. "yyyy-MM-ddTHH:mm:ss.ffffffzzz",
  72. "yyyy-MM-ddTHH:mm:ss.fffffffzzz",
  73. "yyyy-MM-ddTHH:mm:ssZ",
  74. "yyyy-MM-ddTHH:mm:ss.fZ",
  75. "yyyy-MM-ddTHH:mm:ss.ffZ",
  76. "yyyy-MM-ddTHH:mm:ss.fffZ",
  77. "yyyy-MM-ddTHH:mm:ss.ffffZ",
  78. "yyyy-MM-ddTHH:mm:ss.fffffZ",
  79. "yyyy-MM-ddTHH:mm:ss.ffffffZ",
  80. "yyyy-MM-ddTHH:mm:ss.fffffffZ",
  81. "yyyy-MM-ddTHH:mm:ss",
  82. "yyyy-MM-ddTHH:mm:ss.f",
  83. "yyyy-MM-ddTHH:mm:ss.ff",
  84. "yyyy-MM-ddTHH:mm:ss.fff",
  85. "yyyy-MM-ddTHH:mm:ss.ffff",
  86. "yyyy-MM-ddTHH:mm:ss.fffff",
  87. "yyyy-MM-ddTHH:mm:ss.ffffff",
  88. "yyyy-MM-ddTHH:mm:ss.fffffff",
  89. // time
  90. "HH:mm:ss",
  91. "HH:mm:ss.f",
  92. "HH:mm:ss.ff",
  93. "HH:mm:ss.fff",
  94. "HH:mm:ss.ffff",
  95. "HH:mm:ss.fffff",
  96. "HH:mm:ss.ffffff",
  97. "HH:mm:ss.fffffff",
  98. "HH:mm:sszzz",
  99. "HH:mm:ss.fzzz",
  100. "HH:mm:ss.ffzzz",
  101. "HH:mm:ss.fffzzz",
  102. "HH:mm:ss.ffffzzz",
  103. "HH:mm:ss.fffffzzz",
  104. "HH:mm:ss.ffffffzzz",
  105. "HH:mm:ss.fffffffzzz",
  106. "HH:mm:ssZ",
  107. "HH:mm:ss.fZ",
  108. "HH:mm:ss.ffZ",
  109. "HH:mm:ss.fffZ",
  110. "HH:mm:ss.ffffZ",
  111. "HH:mm:ss.fffffZ",
  112. "HH:mm:ss.ffffffZ",
  113. "HH:mm:ss.fffffffZ",
  114. #endif
  115. // date
  116. "yyyy-MM-dd",
  117. "yyyy-MM-ddzzz",
  118. "yyyy-MM-ddZ",
  119. // gYearMonth
  120. "yyyy-MM",
  121. "yyyy-MMzzz",
  122. "yyyy-MMZ",
  123. // gYear
  124. "yyyy",
  125. "yyyyzzz",
  126. "yyyyZ",
  127. // gMonthDay
  128. "--MM-dd",
  129. "--MM-ddzzz",
  130. "--MM-ddZ",
  131. // gDay
  132. "---dd",
  133. "---ddzzz",
  134. "---ddZ",
  135. };
  136. #if NET_2_0
  137. static readonly string [] defaultDateTimeFormats = new string [] {
  138. "yyyy-MM-ddTHH:mm:ss", // dateTime(1)
  139. "yyyy-MM-ddTHH:mm:ss.FFFFFFF", // dateTime(2)
  140. "yyyy-MM-dd", // date
  141. "HH:mm:ss", // time
  142. "yyyy-MM", // gYearMonth
  143. "yyyy", // gYear
  144. "--MM-dd", // gMonthDay
  145. "---dd", // gDay
  146. };
  147. static readonly string [] roundtripDateTimeFormats;
  148. static readonly string [] localDateTimeFormats;
  149. static readonly string [] utcDateTimeFormats;
  150. static readonly string [] unspecifiedDateTimeFormats;
  151. static XmlConvert ()
  152. {
  153. int l = defaultDateTimeFormats.Length;
  154. roundtripDateTimeFormats = new string [l];
  155. localDateTimeFormats = new string [l];
  156. utcDateTimeFormats = new string [l * 3];
  157. unspecifiedDateTimeFormats = new string [l * 4];
  158. for (int i = 0; i < l; i++) {
  159. string s = defaultDateTimeFormats [i];
  160. localDateTimeFormats [i] = s + "zzz";
  161. roundtripDateTimeFormats [i] = s + 'K';
  162. utcDateTimeFormats [i * 3] = s;
  163. utcDateTimeFormats [i * 3 + 1] = s + 'Z';
  164. utcDateTimeFormats [i * 3 + 2] = s + "zzz";
  165. unspecifiedDateTimeFormats [i * 4] = s;
  166. unspecifiedDateTimeFormats [i * 4 + 1] = localDateTimeFormats [i];
  167. unspecifiedDateTimeFormats [i * 4 + 2] = roundtripDateTimeFormats [i];
  168. unspecifiedDateTimeFormats [i * 4 + 3] = utcDateTimeFormats [i];
  169. }
  170. }
  171. #endif
  172. static DateTimeStyles _defaultStyle = DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite;
  173. public XmlConvert()
  174. {}
  175. private static string TryDecoding (string s)
  176. {
  177. if (s == null || s.Length < 6)
  178. return s;
  179. char c = '\uFFFF';
  180. try {
  181. c = (char) Int32.Parse (s.Substring (1, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
  182. } catch {
  183. return s [0] + DecodeName (s.Substring (1));
  184. }
  185. if (s.Length == 6)
  186. return c.ToString ();
  187. return c + DecodeName (s.Substring (6));
  188. }
  189. public static string DecodeName (string name)
  190. {
  191. if (name == null || name.Length == 0)
  192. return name;
  193. int pos = name.IndexOf ('_');
  194. if (pos == -1 || pos + 6 >= name.Length)
  195. return name;
  196. if ((name [pos + 1] != 'X' && name [pos + 1] != 'x') || name [pos + 6] != '_')
  197. return name [0] + DecodeName (name.Substring (1));
  198. return name.Substring (0, pos) + TryDecoding (name.Substring (pos + 1));
  199. }
  200. public static string EncodeLocalName (string name)
  201. {
  202. if (name == null)
  203. return name;
  204. string encoded = EncodeName (name);
  205. int pos = encoded.IndexOf (':');
  206. if (pos == -1)
  207. return encoded;
  208. return encoded.Replace (":", encodedColon);
  209. }
  210. internal static bool IsInvalid (char c, bool firstOnlyLetter)
  211. {
  212. if (c == ':') // Special case. allowed in EncodeName, but encoded in EncodeLocalName
  213. return false;
  214. if (firstOnlyLetter)
  215. return !XmlChar.IsFirstNameChar (c);
  216. else
  217. return !XmlChar.IsNameChar (c);
  218. }
  219. private static string EncodeName (string name, bool nmtoken)
  220. {
  221. if (name == null || name.Length == 0)
  222. return name;
  223. StringBuilder sb = new StringBuilder ();
  224. int length = name.Length;
  225. for (int i = 0; i < length; i++) {
  226. char c = name [i];
  227. if (IsInvalid (c, i == 0 && !nmtoken))
  228. sb.AppendFormat ("_x{0:X4}_", (int) c);
  229. else if (c == '_' && i + 6 < length && name [i+1] == 'x' && name [i + 6] == '_')
  230. sb.Append ("_x005F_");
  231. else
  232. sb.Append (c);
  233. }
  234. return sb.ToString ();
  235. }
  236. public static string EncodeName (string name)
  237. {
  238. return EncodeName (name, false);
  239. }
  240. public static string EncodeNmToken (string name)
  241. {
  242. if (name == String.Empty)
  243. throw new XmlException ("Invalid NmToken: ''");
  244. return EncodeName (name, true);
  245. }
  246. // {true, false, 1, 0}
  247. public static bool ToBoolean(string s)
  248. {
  249. s = s.Trim (XmlChar.WhitespaceChars);
  250. switch(s)
  251. {
  252. case "1":
  253. return true;
  254. case "true":
  255. return true;
  256. case "0":
  257. return false;
  258. case "false":
  259. return false;
  260. default:
  261. throw new FormatException(s + " is not a valid boolean value");
  262. }
  263. }
  264. // LAMESPEC: It has been documented as public, but is marked as internal.
  265. internal static string ToBinHexString (byte [] buffer)
  266. {
  267. StringWriter w = new StringWriter ();
  268. WriteBinHex (buffer, 0, buffer.Length, w);
  269. return w.ToString ();
  270. }
  271. internal static void WriteBinHex (byte [] buffer, int index, int count, TextWriter w)
  272. {
  273. if (buffer == null)
  274. throw new ArgumentNullException ("buffer");
  275. if (index < 0) {
  276. throw new ArgumentOutOfRangeException (
  277. #if !NET_2_1
  278. "index", index,
  279. #endif
  280. "index must be non negative integer.");
  281. }
  282. if (count < 0) {
  283. throw new ArgumentOutOfRangeException (
  284. #if !NET_2_1
  285. "count", count,
  286. #endif
  287. "count must be non negative integer.");
  288. }
  289. if (buffer.Length < index + count)
  290. throw new ArgumentOutOfRangeException ("index and count must be smaller than the length of the buffer.");
  291. // Copied from XmlTextWriter.WriteBinHex ()
  292. int end = index + count;
  293. for (int i = index; i < end; i++) {
  294. int val = buffer [i];
  295. int high = val >> 4;
  296. int low = val & 15;
  297. if (high > 9)
  298. w.Write ((char) (high + 55));
  299. else
  300. w.Write ((char) (high + 0x30));
  301. if (low > 9)
  302. w.Write ((char) (low + 55));
  303. else
  304. w.Write ((char) (low + 0x30));
  305. }
  306. }
  307. public static byte ToByte(string s)
  308. {
  309. return Byte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
  310. }
  311. public static char ToChar(string s)
  312. {
  313. #if !NET_2_1
  314. return Char.Parse(s);
  315. #else
  316. if (s == null)
  317. throw new ArgumentNullException ("s");
  318. if (s.Length != 1)
  319. throw new FormatException ("String contain more than one char");
  320. return s [0];
  321. #endif
  322. }
  323. #if NET_2_0
  324. [Obsolete]
  325. #endif
  326. public static DateTime ToDateTime (string s)
  327. {
  328. return ToDateTime (s, datetimeFormats);
  329. }
  330. #if NET_2_0
  331. public static DateTime ToDateTime (string value, XmlDateTimeSerializationMode mode)
  332. {
  333. DateTime dt;
  334. switch (mode) {
  335. case XmlDateTimeSerializationMode.Local:
  336. dt = ToDateTime (value, localDateTimeFormats);
  337. return dt == DateTime.MinValue || dt == DateTime.MaxValue ? dt : dt.ToLocalTime ();
  338. case XmlDateTimeSerializationMode.RoundtripKind:
  339. return ToDateTime (value, roundtripDateTimeFormats, _defaultStyle | DateTimeStyles.RoundtripKind);
  340. case XmlDateTimeSerializationMode.Utc:
  341. dt = ToDateTime (value, utcDateTimeFormats);
  342. return dt == DateTime.MinValue || dt == DateTime.MaxValue ? dt : dt.ToUniversalTime ();
  343. case XmlDateTimeSerializationMode.Unspecified:
  344. return ToDateTime (value, unspecifiedDateTimeFormats);
  345. default:
  346. return ToDateTime (value, defaultDateTimeFormats);
  347. }
  348. }
  349. #endif
  350. public static DateTime ToDateTime(string s, string format)
  351. {
  352. //DateTimeFormatInfo d = new DateTimeFormatInfo();
  353. //d.FullDateTimePattern = format;
  354. //return DateTime.Parse(s, d);
  355. DateTimeStyles style = DateTimeStyles.AllowLeadingWhite |
  356. DateTimeStyles.AllowTrailingWhite;
  357. return DateTime.ParseExact (s, format, DateTimeFormatInfo.InvariantInfo, style);
  358. }
  359. public static DateTime ToDateTime(string s, string[] formats)
  360. {
  361. return ToDateTime (s, formats, _defaultStyle);
  362. }
  363. private static DateTime ToDateTime (string s, string [] formats, DateTimeStyles style)
  364. {
  365. return DateTime.ParseExact (s, formats, DateTimeFormatInfo.InvariantInfo, style);
  366. }
  367. public static Decimal ToDecimal(string s)
  368. {
  369. return Decimal.Parse(s, CultureInfo.InvariantCulture);
  370. }
  371. public static double ToDouble(string s)
  372. {
  373. if (s == null)
  374. throw new ArgumentNullException();
  375. float f = TryParseStringFloatConstants (s);
  376. if (f != 0)
  377. return f;
  378. return Double.Parse (s, floatStyle, CultureInfo.InvariantCulture);
  379. }
  380. static float TryParseStringFloatConstants (string s)
  381. {
  382. int sidx = 0;
  383. while (sidx < s.Length && Char.IsWhiteSpace (s [sidx]))
  384. sidx++;
  385. if (sidx == s.Length)
  386. throw new FormatException ();
  387. int sEndPos = s.Length - 1;
  388. while (Char.IsWhiteSpace (s [sEndPos]))
  389. sEndPos--;
  390. if (TryParseStringConstant ("NaN", s, sidx, sEndPos))
  391. return Single.NaN;
  392. if (TryParseStringConstant ("INF", s, sidx, sEndPos))
  393. return Single.PositiveInfinity;
  394. if (TryParseStringConstant ("-INF", s, sidx, sEndPos))
  395. return Single.NegativeInfinity;
  396. // Handle these here because Single.Parse("Infinity") is invalid while XmlConvert.ToSingle("Infinity") is valid.
  397. if (TryParseStringConstant ("Infinity", s, sidx, sEndPos))
  398. return Single.PositiveInfinity;
  399. if (TryParseStringConstant ("-Infinity", s, sidx, sEndPos))
  400. return Single.NegativeInfinity;
  401. return 0;
  402. }
  403. static bool TryParseStringConstant (string format, string s, int start, int end)
  404. {
  405. return end - start + 1 == format.Length && String.CompareOrdinal (format, 0, s, start, format.Length) == 0;
  406. }
  407. public static Guid ToGuid (string s)
  408. {
  409. try {
  410. return new Guid(s);
  411. } catch (FormatException ex) {
  412. throw new FormatException (String.Format ("Invalid Guid input '{0}'", ex.InnerException));
  413. }
  414. }
  415. public static short ToInt16(string s)
  416. {
  417. return Int16.Parse (s, integerStyle, CultureInfo.InvariantCulture);
  418. }
  419. public static int ToInt32(string s)
  420. {
  421. return Int32.Parse (s, integerStyle, CultureInfo.InvariantCulture);
  422. }
  423. public static long ToInt64(string s)
  424. {
  425. return Int64.Parse (s, integerStyle, CultureInfo.InvariantCulture);
  426. }
  427. [CLSCompliant (false)]
  428. public static SByte ToSByte(string s)
  429. {
  430. return SByte.Parse(s, integerStyle, CultureInfo.InvariantCulture);
  431. }
  432. public static float ToSingle(string s)
  433. {
  434. if (s == null)
  435. throw new ArgumentNullException();
  436. float f = TryParseStringFloatConstants (s);
  437. if (f != 0)
  438. return f;
  439. return Single.Parse(s, floatStyle, CultureInfo.InvariantCulture);
  440. }
  441. public static string ToString(Guid value)
  442. {
  443. return value.ToString("D", CultureInfo.InvariantCulture);
  444. }
  445. public static string ToString(int value)
  446. {
  447. return value.ToString(CultureInfo.InvariantCulture);
  448. }
  449. public static string ToString(short value)
  450. {
  451. return value.ToString(CultureInfo.InvariantCulture);
  452. }
  453. public static string ToString(byte value)
  454. {
  455. return value.ToString(CultureInfo.InvariantCulture);
  456. }
  457. public static string ToString(long value)
  458. {
  459. return value.ToString(CultureInfo.InvariantCulture);
  460. }
  461. public static string ToString(char value)
  462. {
  463. return value.ToString(CultureInfo.InvariantCulture);
  464. }
  465. public static string ToString(bool value)
  466. {
  467. if (value) return "true";
  468. return "false";
  469. }
  470. [CLSCompliant (false)]
  471. public static string ToString(SByte value)
  472. {
  473. return value.ToString(CultureInfo.InvariantCulture);
  474. }
  475. public static string ToString(Decimal value)
  476. {
  477. return value.ToString (CultureInfo.InvariantCulture);
  478. }
  479. [CLSCompliant (false)]
  480. public static string ToString(UInt64 value)
  481. {
  482. return value.ToString(CultureInfo.InvariantCulture);
  483. }
  484. public static string ToString (TimeSpan value)
  485. {
  486. if (value == TimeSpan.Zero)
  487. return "PT0S";
  488. StringBuilder builder = new StringBuilder ();
  489. if (value.Ticks < 0) {
  490. if (value == TimeSpan.MinValue)
  491. return "-P10675199DT2H48M5.4775808S"; // There's one fewer tick on the positive side, so we cannot Negate this value; just hard-code it
  492. builder.Append ('-');
  493. value = value.Negate ();
  494. }
  495. builder.Append ('P');
  496. if (value.Days > 0)
  497. builder.Append (value.Days).Append ('D');
  498. long ticks = value.Ticks % TimeSpan.TicksPerMillisecond;
  499. if (value.Days > 0 || value.Hours > 0 || value.Minutes > 0 || value.Seconds > 0 || value.Milliseconds > 0 || ticks > 0) {
  500. builder.Append('T');
  501. if (value.Hours > 0)
  502. builder.Append (value.Hours).Append ('H');
  503. if (value.Minutes > 0)
  504. builder.Append (value.Minutes).Append ('M');
  505. if (value.Seconds > 0 || value.Milliseconds > 0 || ticks > 0) {
  506. builder.Append (value.Seconds);
  507. bool trimZero = true;
  508. if (ticks > 0)
  509. builder.Append ('.').AppendFormat ("{0:0000000}", value.Ticks % TimeSpan.TicksPerSecond);
  510. else if (value.Milliseconds > 0)
  511. builder.Append ('.').AppendFormat ("{0:000}", value.Milliseconds);
  512. else
  513. trimZero = false;
  514. if (trimZero)
  515. while (builder [builder.Length - 1] == '0')
  516. builder.Remove (builder.Length - 1, 1);
  517. builder.Append ('S');
  518. }
  519. }
  520. return builder.ToString ();
  521. }
  522. public static string ToString(double value)
  523. {
  524. if (Double.IsNegativeInfinity(value)) return "-INF";
  525. if (Double.IsPositiveInfinity(value)) return "INF";
  526. if (Double.IsNaN(value)) return "NaN";
  527. return value.ToString("R", CultureInfo.InvariantCulture);
  528. }
  529. public static string ToString(float value)
  530. {
  531. if (Single.IsNegativeInfinity(value)) return "-INF";
  532. if (Single.IsPositiveInfinity(value)) return "INF";
  533. if (Single.IsNaN(value)) return "NaN";
  534. return value.ToString("R", CultureInfo.InvariantCulture);
  535. }
  536. [CLSCompliant (false)]
  537. public static string ToString(UInt32 value)
  538. {
  539. return value.ToString(CultureInfo.InvariantCulture);
  540. }
  541. [CLSCompliant (false)]
  542. public static string ToString(UInt16 value)
  543. {
  544. return value.ToString(CultureInfo.InvariantCulture);
  545. }
  546. #if NET_2_0
  547. [Obsolete]
  548. #endif
  549. public static string ToString (DateTime value)
  550. {
  551. return value.ToString ("yyyy-MM-ddTHH:mm:ss.fffffffzzz", CultureInfo.InvariantCulture);
  552. }
  553. #if NET_2_0
  554. public static string ToString (DateTime value, XmlDateTimeSerializationMode mode)
  555. {
  556. // Unlike usual DateTime formatting, it preserves
  557. // MaxValue/MinValue as is.
  558. switch (mode) {
  559. case XmlDateTimeSerializationMode.Local:
  560. return (value == DateTime.MinValue ? DateTime.MinValue : value == DateTime.MaxValue ? value : value.ToLocalTime ()).ToString (
  561. "yyyy-MM-ddTHH:mm:ss.FFFFFFFzzz",
  562. CultureInfo.InvariantCulture);
  563. case XmlDateTimeSerializationMode.RoundtripKind:
  564. return value.ToString (
  565. "yyyy-MM-ddTHH:mm:ss.FFFFFFFK",
  566. CultureInfo.InvariantCulture);
  567. default:
  568. return value.ToString (
  569. "yyyy-MM-ddTHH:mm:ss.FFFFFFFzzz",
  570. CultureInfo.InvariantCulture);
  571. case XmlDateTimeSerializationMode.Utc:
  572. return (value == DateTime.MinValue ? DateTime.MinValue : value == DateTime.MaxValue ? value : value.ToUniversalTime ()).ToString (
  573. "yyyy-MM-ddTHH:mm:ss.FFFFFFFZ",
  574. CultureInfo.InvariantCulture);
  575. case XmlDateTimeSerializationMode.Unspecified:
  576. return value.ToString (
  577. "yyyy-MM-ddTHH:mm:ss.FFFFFFF",
  578. CultureInfo.InvariantCulture);
  579. }
  580. }
  581. #endif
  582. public static string ToString(DateTime value, string format)
  583. {
  584. return value.ToString(format, CultureInfo.InvariantCulture);
  585. }
  586. public static TimeSpan ToTimeSpan(string s)
  587. {
  588. s = s.Trim (XmlChar.WhitespaceChars);
  589. if (s.Length == 0)
  590. throw new FormatException ("Invalid format string for duration schema datatype.");
  591. int start = 0;
  592. if (s [0] == '-')
  593. start = 1;
  594. bool minusValue = (start == 1);
  595. if (s [start] != 'P')
  596. throw new FormatException ("Invalid format string for duration schema datatype.");
  597. start++;
  598. int parseStep = 0;
  599. int days = 0;
  600. bool isTime = false;
  601. int hours = 0;
  602. int minutes = 0;
  603. int seconds = 0;
  604. long ticks = 0;
  605. int parsedDigits = 0;
  606. bool error = false;
  607. int i = start;
  608. while (i < s.Length) {
  609. if (s [i] == 'T') {
  610. isTime = true;
  611. parseStep = 4;
  612. i++;
  613. start = i;
  614. continue;
  615. }
  616. for (; i < s.Length; i++)
  617. if (s [i] < '0' || '9' < s [i])
  618. break;
  619. if (parseStep == 7)
  620. parsedDigits = i - start;
  621. int value = int.Parse (s.Substring (start, i - start), CultureInfo.InvariantCulture);
  622. if (parseStep == 7) {
  623. // adjust to 7 digits so that it makes sense as millisecond digits
  624. for (; parsedDigits > 7; parsedDigits--)
  625. value /= 10;
  626. for (; parsedDigits < 7; parsedDigits++)
  627. value *= 10;
  628. }
  629. switch (s [i]) {
  630. case 'Y':
  631. days += value * 365;
  632. if (parseStep > 0)
  633. error = true;
  634. else
  635. parseStep = 1;
  636. break;
  637. case 'M':
  638. if (parseStep < 2) {
  639. days += 365 * (value / 12) + 30 * (value % 12);
  640. parseStep = 2;
  641. } else if (isTime && parseStep < 6) {
  642. minutes = value;
  643. parseStep = 6;
  644. }
  645. else
  646. error = true;
  647. break;
  648. case 'D':
  649. days += value;
  650. if (parseStep > 2)
  651. error = true;
  652. else
  653. parseStep = 3;
  654. break;
  655. case 'H':
  656. hours = value;
  657. if (!isTime || parseStep > 4)
  658. error = true;
  659. else
  660. parseStep = 5;
  661. break;
  662. case 'S':
  663. if (parseStep == 7)
  664. ticks = value;
  665. else
  666. seconds = value;
  667. if (!isTime || parseStep > 7)
  668. error = true;
  669. else
  670. parseStep = 8;
  671. break;
  672. case '.':
  673. if (parseStep > 7)
  674. error = true;
  675. seconds = value;
  676. parseStep = 7;
  677. break;
  678. default:
  679. error = true;
  680. break;
  681. }
  682. if (error)
  683. break;
  684. ++i;
  685. start = i;
  686. }
  687. if (error)
  688. throw new FormatException ("Invalid format string for duration schema datatype.");
  689. TimeSpan ts = new TimeSpan (days, hours, minutes, seconds);
  690. if (minusValue)
  691. return TimeSpan.FromTicks (- (ts.Ticks + ticks));
  692. else
  693. return TimeSpan.FromTicks (ts.Ticks + ticks);
  694. }
  695. [CLSCompliant (false)]
  696. public static UInt16 ToUInt16(string s)
  697. {
  698. return UInt16.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
  699. }
  700. [CLSCompliant (false)]
  701. public static UInt32 ToUInt32(string s)
  702. {
  703. return UInt32.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
  704. }
  705. [CLSCompliant (false)]
  706. public static UInt64 ToUInt64(string s)
  707. {
  708. return UInt64.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
  709. }
  710. public static string VerifyName (string name)
  711. {
  712. if (name == null || name.Length == 0)
  713. throw new ArgumentNullException("name");
  714. if (!XmlChar.IsName (name))
  715. throw new XmlException("'" + name + "' is not a valid XML Name");
  716. return name;
  717. }
  718. public static string VerifyNCName (string ncname)
  719. {
  720. if (ncname == null || ncname.Length == 0)
  721. throw new ArgumentNullException("ncname");
  722. if (!XmlChar.IsNCName (ncname))
  723. throw new XmlException ("'" + ncname + "' is not a valid XML NCName");
  724. return ncname;
  725. }
  726. #if NET_2_0
  727. public static string VerifyTOKEN (string name)
  728. #else
  729. internal static string VerifyTOKEN (string name)
  730. #endif
  731. {
  732. if (name == null)
  733. throw new ArgumentNullException("name");
  734. if (name.Length == 0)
  735. return name;
  736. if (XmlChar.IsWhitespace (name [0]) ||
  737. XmlChar.IsWhitespace (name [name.Length - 1]))
  738. throw new XmlException ("Whitespace characters (#xA, #xD, #x9, #x20) are not allowed as leading or trailing whitespaces of xs:token.");
  739. for (int i = 0; i < name.Length; i++)
  740. if (XmlChar.IsWhitespace (name [i]) && name [i] != ' ')
  741. throw new XmlException ("Either #xA, #xD or #x9 are not allowed inside xs:token.");
  742. return name;
  743. }
  744. #if NET_2_0
  745. public static string VerifyNMTOKEN (string name)
  746. #else
  747. internal static string VerifyNMTOKEN (string name)
  748. #endif
  749. {
  750. if (name == null)
  751. throw new ArgumentNullException("name");
  752. if (!XmlChar.IsNmToken (name))
  753. throw new XmlException("'" + name + "' is not a valid XML NMTOKEN");
  754. return name;
  755. }
  756. // It is documented as public method, but in fact it is not.
  757. internal static byte [] FromBinHexString (string s)
  758. {
  759. char [] chars = s.ToCharArray ();
  760. byte [] bytes = new byte [chars.Length / 2 + chars.Length % 2];
  761. FromBinHexString (chars, 0, chars.Length, bytes);
  762. return bytes;
  763. }
  764. internal static int FromBinHexString (char [] chars, int offset, int charLength, byte [] buffer)
  765. {
  766. int bufIndex = offset;
  767. for (int i = 0; i < charLength - 1; i += 2) {
  768. buffer [bufIndex] = (chars [i] > '9' ?
  769. (byte) (chars [i] - 'A' + 10) :
  770. (byte) (chars [i] - '0'));
  771. buffer [bufIndex] <<= 4;
  772. buffer [bufIndex] += chars [i + 1] > '9' ?
  773. (byte) (chars [i + 1] - 'A' + 10) :
  774. (byte) (chars [i + 1] - '0');
  775. bufIndex++;
  776. }
  777. if (charLength %2 != 0)
  778. buffer [bufIndex++] = (byte)
  779. ((chars [charLength - 1] > '9' ?
  780. (byte) (chars [charLength - 1] - 'A' + 10) :
  781. (byte) (chars [charLength - 1] - '0'))
  782. << 4);
  783. return bufIndex - offset;
  784. }
  785. #if NET_2_0 // actually NET_3_5
  786. #if !TARGET_JVM
  787. public static DateTimeOffset ToDateTimeOffset (string s)
  788. {
  789. return ToDateTimeOffset (s, datetimeFormats);
  790. }
  791. public static DateTimeOffset ToDateTimeOffset (string s, string format)
  792. {
  793. return DateTimeOffset.ParseExact (s, format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
  794. }
  795. public static DateTimeOffset ToDateTimeOffset (string s, string [] formats)
  796. {
  797. DateTimeStyles style = DateTimeStyles.AllowLeadingWhite |
  798. DateTimeStyles.AllowTrailingWhite |
  799. DateTimeStyles.AssumeUniversal;
  800. return DateTimeOffset.ParseExact (s, formats, CultureInfo.InvariantCulture, style);
  801. }
  802. public static string ToString (DateTimeOffset value)
  803. {
  804. return ToString (value, "yyyy-MM-ddTHH:mm:ss.FFFFFFFzzz");
  805. }
  806. public static string ToString (DateTimeOffset value, string format)
  807. {
  808. return value.ToString (format, CultureInfo.InvariantCulture);
  809. }
  810. #endif
  811. // it is used only from 2.1 System.Xml.Serialization.dll from
  812. // MS Silverlight SDK. We don't use it so far.
  813. internal static Uri ToUri (string s)
  814. {
  815. return new Uri (s, UriKind.RelativeOrAbsolute);
  816. }
  817. #endif
  818. }
  819. }