XmlReaderExtensions.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. // Copyright (c) Craftwork Games. All rights reserved.
  2. // Licensed under the MIT license.
  3. // See LICENSE file in the project root for full license information.
  4. using System;
  5. using System.Xml;
  6. using Microsoft.Xna.Framework;
  7. namespace MonoGame.Extended.Serialization.Xml;
  8. /// <summary>
  9. /// Provides extension methods for <see cref="XmlReader"/> to simplify reading and parsing XML Attributes into
  10. /// strong-typed values.
  11. /// </summary>
  12. public static class XmlReaderExtensions
  13. {
  14. /// <summary>
  15. /// Reads an XML attribute as an <see langword="int"/> value.
  16. /// </summary>
  17. /// <param name="reader">The XML reader instance.</param>
  18. /// <param name="attributeName">The name of the attribute to read.</param>
  19. /// <returns>The <see langword="int"/> value parsed from the value of the specified attribute.</returns>
  20. /// <exception cref="XmlException">
  21. /// Thrown when the attribute is missing, or when the attribute value cannot be parsed as an <see langword="int"/>.
  22. /// </exception>
  23. public static int GetAttributeInt(this XmlReader reader, string attributeName)
  24. {
  25. string value = reader.GetAttribute(attributeName);
  26. if (value == null)
  27. {
  28. throw new XmlException($"Required attribute '{attributeName}' is missing.");
  29. }
  30. try
  31. {
  32. return int.Parse(value);
  33. }
  34. catch (Exception ex) when (ex is FormatException || ex is OverflowException)
  35. {
  36. throw new XmlException(
  37. $"Invalid integer format for attribute '{attributeName}'. Expected integer, but got '{value}'",
  38. ex
  39. );
  40. }
  41. }
  42. /// <summary>
  43. /// Reads an XML attribute as a <see langword="float"/> value.
  44. /// </summary>
  45. /// <param name="reader">The XML reader instance.</param>
  46. /// <param name="attributeName">The name of the attribute to read.</param>
  47. /// <returns>The <see langword="float"/> value parsed from the specified attribute.</returns>
  48. /// <exception cref="XmlException">
  49. /// Thrown when the attribute is missing, or when the attribute value cannot be parsed as a <see langword="float"/>.
  50. /// </exception>
  51. public static float GetAttributeFloat(this XmlReader reader, string attributeName)
  52. {
  53. string value = reader.GetAttribute(attributeName);
  54. if (value == null)
  55. {
  56. throw new XmlException($"Required attribute '{attributeName}' is missing.");
  57. }
  58. try
  59. {
  60. return float.Parse(value);
  61. }
  62. catch (Exception ex) when (ex is FormatException || ex is OverflowException)
  63. {
  64. throw new XmlException(
  65. $"Invalid float format for attribute '{attributeName}'. Expected float, but got '{value}'",
  66. ex
  67. );
  68. }
  69. }
  70. /// <summary>
  71. /// Reads an XML attribute as a <see langword="bool"/> value.
  72. /// </summary>
  73. /// <param name="reader">The XML reader instance.</param>
  74. /// <param name="attributeName">The name of the attribute to read.</param>
  75. /// <returns>The <see langword="bool"/> value parsed from the value of the specified attribute.</returns>
  76. /// <exception cref="XmlException">
  77. /// Thrown when the attribute is missing, or when the attribute value cannot be parsed as a <see langword="bool"/>.
  78. /// </exception>
  79. public static bool GetAttributeBool(this XmlReader reader, string attributeName)
  80. {
  81. string value = reader.GetAttribute(attributeName);
  82. if (value == null)
  83. {
  84. throw new XmlException($"Required attribute '{attributeName}' is missing.");
  85. }
  86. try
  87. {
  88. return bool.Parse(value);
  89. }
  90. catch (Exception ex) when (ex is FormatException)
  91. {
  92. throw new XmlException(
  93. $"Invalid bool format for attribute '{attributeName}'. Expected 'true' or 'false' but got '{value}'",
  94. ex
  95. );
  96. }
  97. }
  98. /// <summary>
  99. /// Reads an XML attribute as an enumeration value.
  100. /// </summary>
  101. /// <typeparam name="T">The enumeration type to parse.</typeparam>
  102. /// <param name="reader">The XML reader instance.</param>
  103. /// <param name="attributeName">The name of the attribute to read.</param>
  104. /// <returns>The enumeration value parsed from the value of the specified attribute.</returns>
  105. /// <exception cref="XmlException">
  106. /// Thrown when the attribute is missing, or when the attribute value cannot be parsed as the specified enumeration type.
  107. /// </exception>
  108. public static T GetAttributeEnum<T>(this XmlReader reader, string attributeName) where T : struct, Enum
  109. {
  110. string value = reader.GetAttribute(attributeName);
  111. if (value == null)
  112. {
  113. throw new XmlException($"Required attribute '{attributeName}' is missing.");
  114. }
  115. try
  116. {
  117. return Enum.Parse<T>(value);
  118. }
  119. catch (Exception ex) when (ex is ArgumentException)
  120. {
  121. throw new XmlException(
  122. $"Invalid {typeof(T).Name} format for attribute '{attributeName}'. Expected a {typeof(T).Name} value but got '{value}'",
  123. ex
  124. );
  125. }
  126. }
  127. /// <summary>
  128. /// Reads an XML attribute as a <see cref="Rectangle"/> value.
  129. /// </summary>
  130. /// <param name="reader">The XML reader instance.</param>
  131. /// <param name="attributeName">The name of the attribute to read.</param>
  132. /// <returns>The <see cref="Rectangle"/> value parsed from the value of the specified attribute.</returns>
  133. /// <exception cref="XmlException">
  134. /// Thrown when the attribute is missing, or when the attribute value cannot be parsed as a <see cref="Rectangle"/>.
  135. /// </exception>
  136. public static Rectangle GetAttributeRectangle(this XmlReader reader, string attributeName)
  137. {
  138. string value = reader.GetAttribute(attributeName);
  139. if (value == null)
  140. {
  141. throw new XmlException($"Required attribute '{attributeName}' is missing.");
  142. }
  143. string[] split = value.Split(',', StringSplitOptions.RemoveEmptyEntries);
  144. try
  145. {
  146. if (split.Length != 4)
  147. {
  148. throw new InvalidOperationException($"{nameof(Rectangle)} attribute must contain four integer values separated by a comma");
  149. }
  150. int x = int.Parse(split[0]);
  151. int y = int.Parse(split[1]);
  152. int width = int.Parse(split[2]);
  153. int height = int.Parse(split[3]);
  154. return new Rectangle(x, y, width, height);
  155. }
  156. catch (Exception ex) when (ex is FormatException || ex is OverflowException || ex is InvalidOperationException)
  157. {
  158. throw new XmlException(
  159. $"Invalid {nameof(Rectangle)} format for attribute '{attributeName}'. Expected 'x,y,width,height' but got '{value}'",
  160. ex
  161. );
  162. }
  163. }
  164. /// <summary>
  165. /// Reads an XML attribute as a <see cref="Vector2"/> value.
  166. /// </summary>
  167. /// <param name="reader">The XML reader instance.</param>
  168. /// <param name="attributeName">The name of the attribute to read.</param>
  169. /// <returns>The <see cref="Vector2"/> value parsed from the value of the specified attribute.</returns>
  170. /// <exception cref="XmlException">
  171. /// Thrown when the attribute is missing, or when the attribute value cannot be parsed as a <see cref="Vector2"/>.
  172. /// </exception>
  173. public static Vector2 GetAttributeVector2(this XmlReader reader, string attributeName)
  174. {
  175. string value = reader.GetAttribute(attributeName);
  176. if (value == null)
  177. {
  178. throw new XmlException($"Required attribute '{attributeName}' is missing.");
  179. }
  180. string[] split = value.Split(',', StringSplitOptions.RemoveEmptyEntries);
  181. try
  182. {
  183. if (split.Length != 2)
  184. {
  185. throw new InvalidOperationException($"{nameof(Vector2)} attribute must contain two float values separated by a comma");
  186. }
  187. float x = float.Parse(split[0]);
  188. float y = float.Parse(split[1]);
  189. return new Vector2(x, y);
  190. }
  191. catch (Exception ex) when (ex is FormatException || ex is OverflowException || ex is InvalidOperationException)
  192. {
  193. throw new XmlException(
  194. $"Invalid {nameof(Vector2)} format for attribute '{attributeName}'. Expected 'x,y', but got '{value}'",
  195. ex
  196. );
  197. }
  198. }
  199. /// <summary>
  200. /// Reads an XML attribute as a <see cref="Vector3"/> value.
  201. /// </summary>
  202. /// <param name="reader">The XML reader instance.</param>
  203. /// <param name="attributeName">The name of the attribute to read.</param>
  204. /// <returns>The <see cref="Vector3"/> value parsed from the value of the specified attribute.</returns>
  205. /// <exception cref="XmlException">
  206. /// Thrown when the attribute is missing, or when the attribute value cannot be parsed as a <see cref="Vector3"/>.
  207. /// </exception>
  208. public static Vector3 GetAttributeVector3(this XmlReader reader, string attributeName)
  209. {
  210. string value = reader.GetAttribute(attributeName);
  211. if (value == null)
  212. {
  213. throw new XmlException($"Required attribute '{attributeName}' is missing.");
  214. }
  215. string[] split = value.Split(',', StringSplitOptions.RemoveEmptyEntries);
  216. try
  217. {
  218. if (split.Length != 3)
  219. {
  220. throw new InvalidOperationException($"{nameof(Vector3)} attribute must contain three float values separated by a comma");
  221. }
  222. float x = float.Parse(split[0]);
  223. float y = float.Parse(split[1]);
  224. float z = float.Parse(split[2]);
  225. return new Vector3(x, y, z);
  226. }
  227. catch (Exception ex) when (ex is FormatException || ex is OverflowException || ex is InvalidOperationException)
  228. {
  229. throw new XmlException(
  230. $"Invalid {nameof(Vector3)} format for attribute '{attributeName}'. Expected 'x,y,z', but got '{value}'",
  231. ex
  232. );
  233. }
  234. }
  235. }