XMLUtils.cs 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. using System;
  2. using System.Text;
  3. namespace FairyGUI.Utils
  4. {
  5. /// <summary>
  6. ///
  7. /// </summary>
  8. public class XMLUtils
  9. {
  10. public static string DecodeString(string aSource)
  11. {
  12. int len = aSource.Length;
  13. StringBuilder sb = new StringBuilder();
  14. int pos1 = 0, pos2 = 0;
  15. while (true)
  16. {
  17. pos2 = aSource.IndexOf('&', pos1);
  18. if (pos2 == -1)
  19. {
  20. sb.Append(aSource.Substring(pos1));
  21. break;
  22. }
  23. sb.Append(aSource.Substring(pos1, pos2 - pos1));
  24. pos1 = pos2 + 1;
  25. pos2 = pos1;
  26. int end = Math.Min(len, pos2 + 10);
  27. for (; pos2 < end; pos2++)
  28. {
  29. if (aSource[pos2] == ';')
  30. break;
  31. }
  32. if (pos2 < end && pos2 > pos1)
  33. {
  34. string entity = aSource.Substring(pos1, pos2 - pos1);
  35. int u = 0;
  36. if (entity[0] == '#')
  37. {
  38. if (entity.Length > 1)
  39. {
  40. if (entity[1] == 'x')
  41. u = Convert.ToInt16(entity.Substring(2), 16);
  42. else
  43. u = Convert.ToInt16(entity.Substring(1));
  44. sb.Append((char)u);
  45. pos1 = pos2 + 1;
  46. }
  47. else
  48. sb.Append('&');
  49. }
  50. else
  51. {
  52. switch (entity)
  53. {
  54. case "amp":
  55. u = 38;
  56. break;
  57. case "apos":
  58. u = 39;
  59. break;
  60. case "gt":
  61. u = 62;
  62. break;
  63. case "lt":
  64. u = 60;
  65. break;
  66. case "nbsp":
  67. u = 32;
  68. break;
  69. case "quot":
  70. u = 34;
  71. break;
  72. }
  73. if (u > 0)
  74. {
  75. sb.Append((char)u);
  76. pos1 = pos2 + 1;
  77. }
  78. else
  79. sb.Append('&');
  80. }
  81. }
  82. else
  83. {
  84. sb.Append('&');
  85. }
  86. }
  87. return sb.ToString();
  88. }
  89. private static string[] ESCAPES = new string[] {
  90. "&", "&amp;",
  91. "<", "&lt;",
  92. ">", "&gt;",
  93. "'", "&apos;",
  94. "\"", "&quot;",
  95. "\t", "&#x9;",
  96. "\n", "&#xA;",
  97. "\r", "&#xD;"
  98. };
  99. public static void EncodeString(StringBuilder sb, int start, bool isAttribute = false)
  100. {
  101. int count;
  102. int len = isAttribute ? ESCAPES.Length : 6;
  103. for (int i = 0; i < len; i += 2)
  104. {
  105. count = sb.Length - start;
  106. sb.Replace(ESCAPES[i], ESCAPES[i + 1], start, count);
  107. }
  108. }
  109. public static string EncodeString(string str, bool isAttribute = false)
  110. {
  111. if (string.IsNullOrEmpty(str))
  112. return "";
  113. else
  114. {
  115. StringBuilder sb = new StringBuilder(str);
  116. EncodeString(sb, 0);
  117. return sb.ToString();
  118. }
  119. }
  120. }
  121. }