XmlConvert.cs 13 KB

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