XmlConvert.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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. using System;
  13. using System.Text;
  14. using System.Globalization;
  15. using System.Xml.Schema;
  16. namespace System.Xml {
  17. public class XmlConvert {
  18. const string encodedColon = "_x003A_";
  19. const NumberStyles floatStyle = NumberStyles.AllowCurrencySymbol |
  20. NumberStyles.AllowExponent |
  21. NumberStyles.AllowDecimalPoint |
  22. NumberStyles.AllowLeadingSign;
  23. static readonly string [] datetimeFormats = {
  24. // dateTime
  25. "yyyy-MM-ddTHH:mm:ss",
  26. "yyyy-MM-ddTHH:mm:ss.f",
  27. "yyyy-MM-ddTHH:mm:ss.ff",
  28. "yyyy-MM-ddTHH:mm:ss.fff",
  29. "yyyy-MM-ddTHH:mm:ss.ffff",
  30. "yyyy-MM-ddTHH:mm:ss.fffff",
  31. "yyyy-MM-ddTHH:mm:ss.ffffff",
  32. "yyyy-MM-ddTHH:mm:ss.fffffff",
  33. "yyyy-MM-ddTHH:mm:sszzz",
  34. "yyyy-MM-ddTHH:mm:ss.fzzz",
  35. "yyyy-MM-ddTHH:mm:ss.ffzzz",
  36. "yyyy-MM-ddTHH:mm:ss.fffzzz",
  37. "yyyy-MM-ddTHH:mm:ss.ffffzzz",
  38. "yyyy-MM-ddTHH:mm:ss.fffffzzz",
  39. "yyyy-MM-ddTHH:mm:ss.ffffffzzz",
  40. "yyyy-MM-ddTHH:mm:ss.fffffffzzz",
  41. "yyyy-MM-ddTHH:mm:ssZ",
  42. "yyyy-MM-ddTHH:mm:ss.fZ",
  43. "yyyy-MM-ddTHH:mm:ss.ffZ",
  44. "yyyy-MM-ddTHH:mm:ss.fffZ",
  45. "yyyy-MM-ddTHH:mm:ss.ffffZ",
  46. "yyyy-MM-ddTHH:mm:ss.fffffZ",
  47. "yyyy-MM-ddTHH:mm:ss.ffffffZ",
  48. "yyyy-MM-ddTHH:mm:ss.fffffffZ",
  49. // time
  50. "HH:mm:ss",
  51. "HH:mm:ss.f",
  52. "HH:mm:ss.ff",
  53. "HH:mm:ss.fff",
  54. "HH:mm:ss.ffff",
  55. "HH:mm:ss.fffff",
  56. "HH:mm:ss.ffffff",
  57. "HH:mm:ss.fffffff",
  58. "HH:mm:sszzz",
  59. "HH:mm:ss.fzzz",
  60. "HH:mm:ss.ffzzz",
  61. "HH:mm:ss.fffzzz",
  62. "HH:mm:ss.ffffzzz",
  63. "HH:mm:ss.fffffzzz",
  64. "HH:mm:ss.ffffffzzz",
  65. "HH:mm:ss.fffffffzzz",
  66. "HH:mm:ssZ",
  67. "HH:mm:ss.fZ",
  68. "HH:mm:ss.ffZ",
  69. "HH:mm:ss.fffZ",
  70. "HH:mm:ss.ffffZ",
  71. "HH:mm:ss.fffffZ",
  72. "HH:mm:ss.ffffffZ",
  73. "HH:mm:ss.fffffffZ",
  74. // date
  75. "yyyy-MM-dd",
  76. "yyyy-MM-ddzzz",
  77. "yyyy-MM-ddZ",
  78. // gYearMonth
  79. "yyyy-MM",
  80. "yyyy-MMzzz",
  81. "yyyy-MMZ",
  82. // gYear
  83. "yyyy",
  84. "yyyyzzz",
  85. "yyyyZ",
  86. // gMonthDay
  87. "--MM-dd",
  88. "--MM-ddzzz",
  89. "--MM-ddZ",
  90. // gDay
  91. "---dd",
  92. "---ddzzz",
  93. "---ddZ",
  94. };
  95. public XmlConvert()
  96. {}
  97. private static string TryDecoding (string s)
  98. {
  99. if (s == null || s.Length < 6)
  100. return s;
  101. char c = '\uFFFF';
  102. try {
  103. c = (char) Int32.Parse (s.Substring (1, 4), NumberStyles.HexNumber);
  104. } catch {
  105. return s [0] + DecodeName (s.Substring (1));
  106. }
  107. if (s.Length == 6)
  108. return c.ToString ();
  109. return c + DecodeName (s.Substring (6));
  110. }
  111. public static string DecodeName (string name)
  112. {
  113. if (name == null || name.Length == 0)
  114. return name;
  115. int pos = name.IndexOf ('_');
  116. if (pos == -1 || pos + 6 >= name.Length)
  117. return name;
  118. if ((name [pos + 1] != 'X' && name [pos + 1] != 'x') || name [pos + 6] != '_')
  119. return name [0] + DecodeName (name.Substring (1));
  120. return name.Substring (0, pos) + TryDecoding (name.Substring (pos + 1));
  121. }
  122. public static string EncodeLocalName (string name)
  123. {
  124. string encoded = EncodeName (name);
  125. int pos = encoded.IndexOf (':');
  126. if (pos == -1)
  127. return encoded;
  128. return encoded.Replace (":", encodedColon);
  129. }
  130. internal static bool IsInvalid (char c, bool firstOnlyLetter)
  131. {
  132. if (c == ':') // Special case. allowed in EncodeName, but encoded in EncodeLocalName
  133. return false;
  134. if (firstOnlyLetter)
  135. return !XmlChar.IsFirstNameChar (c);
  136. else
  137. return !XmlChar.IsNameChar (c);
  138. }
  139. private static string EncodeName (string name, bool nmtoken)
  140. {
  141. StringBuilder sb = new StringBuilder ();
  142. int length = name.Length;
  143. for (int i = 0; i < length; i++) {
  144. char c = name [i];
  145. if (IsInvalid (c, i == 0 && !nmtoken))
  146. sb.AppendFormat ("_x{0:X4}_", (int) c);
  147. else if (c == '_' && i + 6 < length && name [i+1] == 'x' && name [i + 6] == '_')
  148. sb.Append ("_x005F_");
  149. else
  150. sb.Append (c);
  151. }
  152. return sb.ToString ();
  153. }
  154. public static string EncodeName (string name)
  155. {
  156. return EncodeName (name, false);
  157. }
  158. public static string EncodeNmToken(string name)
  159. {
  160. return EncodeName (name, true);
  161. }
  162. // {true, false, 1, 0}
  163. public static bool ToBoolean(string s)
  164. {
  165. s = s.Trim (XmlChar.WhitespaceChars);
  166. switch(s)
  167. {
  168. case "1":
  169. return true;
  170. case "true":
  171. return true;
  172. case "0":
  173. return false;
  174. case "false":
  175. return false;
  176. default:
  177. throw new FormatException(s + " is not a valid boolean value");
  178. }
  179. }
  180. public static byte ToByte(string s)
  181. {
  182. return Byte.Parse(s, CultureInfo.InvariantCulture);
  183. }
  184. public static char ToChar(string s)
  185. {
  186. return Char.Parse(s);
  187. }
  188. public static DateTime ToDateTime(string s)
  189. {
  190. return ToDateTime(s, datetimeFormats);
  191. }
  192. public static DateTime ToDateTime(string s, string format)
  193. {
  194. DateTimeFormatInfo d = new DateTimeFormatInfo();
  195. d.FullDateTimePattern = format;
  196. return DateTime.Parse(s, d);
  197. }
  198. public static DateTime ToDateTime(string s, string[] formats)
  199. {
  200. DateTimeStyles style = DateTimeStyles.AllowLeadingWhite |
  201. DateTimeStyles.AllowTrailingWhite;
  202. return DateTime.ParseExact (s, formats, DateTimeFormatInfo.InvariantInfo, style);
  203. }
  204. public static Decimal ToDecimal(string s)
  205. {
  206. return Decimal.Parse(s, CultureInfo.InvariantCulture);
  207. }
  208. public static double ToDouble(string s)
  209. {
  210. if (s == null)
  211. throw new ArgumentNullException();
  212. if (s == "INF")
  213. return Double.PositiveInfinity;
  214. if (s == "-INF")
  215. return Double.NegativeInfinity;
  216. if (s == "NaN")
  217. return Double.NaN;
  218. return Double.Parse (s, floatStyle, CultureInfo.InvariantCulture);
  219. }
  220. public static Guid ToGuid(string s)
  221. {
  222. return new Guid(s);
  223. }
  224. public static short ToInt16(string s)
  225. {
  226. return Int16.Parse(s, CultureInfo.InvariantCulture);
  227. }
  228. public static int ToInt32(string s)
  229. {
  230. return Int32.Parse(s, CultureInfo.InvariantCulture);
  231. }
  232. public static long ToInt64(string s)
  233. {
  234. return Int64.Parse(s, CultureInfo.InvariantCulture);
  235. }
  236. [CLSCompliant (false)]
  237. public static SByte ToSByte(string s)
  238. {
  239. return SByte.Parse(s, CultureInfo.InvariantCulture);
  240. }
  241. public static float ToSingle(string s)
  242. {
  243. if (s == null)
  244. throw new ArgumentNullException();
  245. if (s == "INF")
  246. return Single.PositiveInfinity;
  247. if (s == "-INF")
  248. return Single.NegativeInfinity;
  249. if (s == "NaN")
  250. return Single.NaN;
  251. return Single.Parse(s, floatStyle, CultureInfo.InvariantCulture);
  252. }
  253. public static string ToString(Guid value)
  254. {
  255. return value.ToString("D", CultureInfo.InvariantCulture);
  256. }
  257. public static string ToString(int value)
  258. {
  259. return value.ToString(CultureInfo.InvariantCulture);
  260. }
  261. public static string ToString(short value)
  262. {
  263. return value.ToString(CultureInfo.InvariantCulture);
  264. }
  265. public static string ToString(byte value)
  266. {
  267. return value.ToString(CultureInfo.InvariantCulture);
  268. }
  269. public static string ToString(long value)
  270. {
  271. return value.ToString(CultureInfo.InvariantCulture);
  272. }
  273. public static string ToString(char value)
  274. {
  275. return value.ToString(CultureInfo.InvariantCulture);
  276. }
  277. public static string ToString(bool value)
  278. {
  279. if (value) return "true";
  280. return "false";
  281. }
  282. [CLSCompliant (false)]
  283. public static string ToString(SByte value)
  284. {
  285. return value.ToString(CultureInfo.InvariantCulture);
  286. }
  287. public static string ToString(Decimal value)
  288. {
  289. return value.ToString (CultureInfo.InvariantCulture);
  290. }
  291. [CLSCompliant (false)]
  292. public static string ToString(UInt64 value)
  293. {
  294. return value.ToString(CultureInfo.InvariantCulture);
  295. }
  296. public static string ToString (TimeSpan value)
  297. {
  298. StringBuilder builder = new StringBuilder ();
  299. if (value.Ticks < 0) {
  300. builder.Append ('-');
  301. value = value.Negate ();
  302. }
  303. builder.Append ('P');
  304. if (value.Days > 0)
  305. builder.Append (value.Days).Append ('D');
  306. if (value.Days > 0 || value.Hours > 0 || value.Minutes > 0 || value.Seconds > 0 || value.Milliseconds > 0) {
  307. builder.Append('T');
  308. if (value.Hours > 0)
  309. builder.Append (value.Hours).Append ('H');
  310. if (value.Minutes > 0)
  311. builder.Append (value.Minutes).Append ('M');
  312. if (value.Seconds > 0 || value.Milliseconds > 0) {
  313. builder.Append (value.Seconds);
  314. if (value.Milliseconds > 0)
  315. builder.Append ('.').AppendFormat ("{0:000}", value.Milliseconds);
  316. builder.Append ('S');
  317. }
  318. }
  319. return builder.ToString ();
  320. }
  321. public static string ToString(double value)
  322. {
  323. if (Double.IsNegativeInfinity(value)) return "-INF";
  324. if (Double.IsPositiveInfinity(value)) return "INF";
  325. if (Double.IsNaN(value)) return "NaN";
  326. return value.ToString(CultureInfo.InvariantCulture);
  327. }
  328. public static string ToString(float value)
  329. {
  330. if (Single.IsNegativeInfinity(value)) return "-INF";
  331. if (Single.IsPositiveInfinity(value)) return "INF";
  332. if (Single.IsNaN(value)) return "NaN";
  333. return value.ToString(CultureInfo.InvariantCulture);
  334. }
  335. [CLSCompliant (false)]
  336. public static string ToString(UInt32 value)
  337. {
  338. return value.ToString(CultureInfo.InvariantCulture);
  339. }
  340. [CLSCompliant (false)]
  341. public static string ToString(UInt16 value)
  342. {
  343. return value.ToString(CultureInfo.InvariantCulture);
  344. }
  345. public static string ToString(DateTime value)
  346. {
  347. return value.ToString("yyyy-MM-ddTHH:mm:ss.fffffffzzz", CultureInfo.InvariantCulture);
  348. }
  349. public static string ToString(DateTime value, string format)
  350. {
  351. return value.ToString(format, CultureInfo.InvariantCulture);
  352. }
  353. public static TimeSpan ToTimeSpan(string s)
  354. {
  355. if (s.Length == 0)
  356. throw new ArgumentException ("Invalid format string for duration schema datatype.");
  357. int start = 0;
  358. if (s [0] == '-')
  359. start = 1;
  360. bool minusValue = (start == 1);
  361. if (s [start] != 'P')
  362. throw new ArgumentException ("Invalid format string for duration schema datatype.");
  363. start++;
  364. int parseStep = 0;
  365. int days = 0;
  366. bool isTime = false;
  367. int hours = 0;
  368. int minutes = 0;
  369. int seconds = 0;
  370. bool error = false;
  371. int i = start;
  372. while (i < s.Length) {
  373. if (s [i] == 'T') {
  374. isTime = true;
  375. parseStep = 4;
  376. i++;
  377. start = i;
  378. continue;
  379. }
  380. for (; i < s.Length; i++) {
  381. if (!Char.IsDigit (s [i]))
  382. break;
  383. }
  384. int value = int.Parse (s.Substring (start, i - start));
  385. switch (s [i]) {
  386. case 'Y':
  387. days += value * 365;
  388. if (parseStep > 0)
  389. error = true;
  390. else
  391. parseStep = 1;
  392. break;
  393. case 'M':
  394. if (parseStep < 2) {
  395. days += 365 * (value / 12) + 30 * (value % 12);
  396. parseStep = 2;
  397. } else if (isTime && parseStep < 6) {
  398. minutes = value;
  399. parseStep = 6;
  400. }
  401. else
  402. error = true;
  403. break;
  404. case 'D':
  405. days += value;
  406. if (parseStep > 2)
  407. error = true;
  408. else
  409. parseStep = 3;
  410. break;
  411. case 'H':
  412. hours = value;
  413. if (!isTime || parseStep > 4)
  414. error = true;
  415. else
  416. parseStep = 5;
  417. break;
  418. case 'S':
  419. seconds = value;
  420. if (!isTime || parseStep > 6)
  421. error = true;
  422. else
  423. parseStep = 7;
  424. break;
  425. default:
  426. error = true;
  427. break;
  428. }
  429. if (error)
  430. break;
  431. ++i;
  432. start = i;
  433. }
  434. if (error)
  435. throw new ArgumentException ("Invalid format string for duration schema datatype.");
  436. TimeSpan ts = new TimeSpan (days, hours, minutes, seconds);
  437. return minusValue ? -ts : ts;
  438. }
  439. [CLSCompliant (false)]
  440. public static UInt16 ToUInt16(string s)
  441. {
  442. return UInt16.Parse(s, CultureInfo.InvariantCulture);
  443. }
  444. [CLSCompliant (false)]
  445. public static UInt32 ToUInt32(string s)
  446. {
  447. return UInt32.Parse(s, CultureInfo.InvariantCulture);
  448. }
  449. [CLSCompliant (false)]
  450. public static UInt64 ToUInt64(string s)
  451. {
  452. return UInt64.Parse(s, CultureInfo.InvariantCulture);
  453. }
  454. public static string VerifyName (string name)
  455. {
  456. if(name == null)
  457. throw new ArgumentNullException("name");
  458. if(!XmlChar.IsName (name))
  459. throw new XmlException("'" + name + "' is not a valid XML Name");
  460. return name;
  461. }
  462. public static string VerifyNCName(string ncname)
  463. {
  464. if(ncname == null)
  465. throw new ArgumentNullException("ncname");
  466. if(!XmlChar.IsNCName (ncname))
  467. throw new XmlException ("'" + ncname + "' is not a valid XML NCName");
  468. return ncname;
  469. }
  470. // It is documented as public method, but in fact it is not.
  471. internal static byte [] FromBinHexString (string s)
  472. {
  473. char [] chars = s.ToCharArray ();
  474. byte [] bytes = new byte [chars.Length / 2 + chars.Length % 2];
  475. FromBinHexString (chars, 0, chars.Length, bytes);
  476. return bytes;
  477. }
  478. internal static int FromBinHexString (char [] chars, int offset, int charLength, byte [] buffer)
  479. {
  480. int bufIndex = offset;
  481. for (int i = 0; i < charLength - 1; i += 2) {
  482. buffer [bufIndex] = (chars [i] > '9' ?
  483. (byte) (chars [i] - 'A' + 10) :
  484. (byte) (chars [i] - '0'));
  485. buffer [bufIndex] <<= 4;
  486. buffer [bufIndex] += chars [i + 1] > '9' ?
  487. (byte) (chars [i + 1] - 'A' + 10) :
  488. (byte) (chars [i + 1] - '0');
  489. bufIndex++;
  490. }
  491. if (charLength %2 != 0)
  492. buffer [bufIndex++] = (byte)
  493. ((chars [charLength - 1] > '9' ?
  494. (byte) (chars [charLength - 1] - 'A' + 10) :
  495. (byte) (chars [charLength - 1] - '0'))
  496. << 4);
  497. return bufIndex - offset;
  498. }
  499. }
  500. }