| | | 1 | | using System.Collections; |
| | | 2 | | using System.Reflection; |
| | | 3 | | using System.Xml.Linq; |
| | | 4 | | |
| | | 5 | | namespace Kestrun.Utilities; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Helpers for converting arbitrary objects into <see cref="XElement"/> instances. |
| | | 9 | | /// </summary> |
| | | 10 | | public static class XmlHelper |
| | | 11 | | { |
| | 1 | 12 | | private static readonly XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; |
| | | 13 | | /// <summary> |
| | | 14 | | /// Default maximum recursion depth for object-to-XML conversion. |
| | | 15 | | /// Chosen to balance performance and stack safety for typical object graphs. |
| | | 16 | | /// Adjust if deeper object graphs need to be serialized. |
| | | 17 | | /// </summary> |
| | | 18 | | public const int DefaultMaxDepth = 32; |
| | | 19 | | |
| | | 20 | | /// <summary> |
| | | 21 | | /// Maximum recursion depth for object-to-XML conversion. This value can be adjusted if deeper object graphs need to |
| | | 22 | | /// </summary> |
| | 113 | 23 | | public static int MaxDepth { get; set; } = DefaultMaxDepth; |
| | | 24 | | // Per-call cycle detection now passed explicitly (was ThreadStatic). Avoids potential thread reuse memory retention |
| | | 25 | | // Rationale: |
| | | 26 | | // * ThreadStatic HashSet could retain large object graphs across requests in thread pool threads causing memory b |
| | | 27 | | // * A per-call HashSet has a short lifetime and becomes eligible for GC immediately after serialization completes |
| | | 28 | | // * Passing the set by reference keeps allocation to a single HashSet per root ToXml call (lazy created on first |
| | | 29 | | // * No synchronization needed: the set is confined to the call stack; recursive calls share it by reference. |
| | | 30 | | |
| | | 31 | | /// <summary> |
| | | 32 | | /// Converts an object to an <see cref="XElement"/> with the specified name, handling nulls, primitives, dictionarie |
| | | 33 | | /// </summary> |
| | | 34 | | /// <param name="name">The name of the XML element.</param> |
| | | 35 | | /// <param name="value">The object to convert to XML.</param> |
| | | 36 | | /// <returns>An <see cref="XElement"/> representing the object.</returns> |
| | 13 | 37 | | public static XElement ToXml(string name, object? value) => ToXmlInternal(SanitizeName(name), value, 0, visited: nul |
| | | 38 | | |
| | | 39 | | /// <summary> |
| | | 40 | | /// Internal recursive method to convert an object to XML, with depth tracking and cycle detection. |
| | | 41 | | /// </summary> |
| | | 42 | | /// <param name="name">The name of the XML element.</param> |
| | | 43 | | /// <param name="value">The object to convert to XML.</param> |
| | | 44 | | /// <param name="depth">The current recursion depth.</param> |
| | | 45 | | /// <returns>An <see cref="XElement"/> representing the object.</returns> |
| | | 46 | | /// <param name="visited">Per-call set of already visited reference objects for cycle detection.</param> |
| | | 47 | | private static XElement ToXmlInternal(string name, object? value, int depth, HashSet<object>? visited) |
| | | 48 | | { |
| | | 49 | | // Fast path & terminal cases extracted to helpers for reduced branching complexity. |
| | 112 | 50 | | if (TryHandleTerminal(name, value, depth, ref visited, out var terminal)) |
| | | 51 | | { |
| | 68 | 52 | | return terminal; |
| | | 53 | | } |
| | | 54 | | |
| | | 55 | | // At this point value is non-null complex/reference or value-type object requiring reflection. |
| | 44 | 56 | | var type = value!.GetType(); |
| | 44 | 57 | | var needsCycleTracking = !type.IsValueType; |
| | 44 | 58 | | if (needsCycleTracking && !EnterCycle(value, ref visited, out var cycleElem)) |
| | | 59 | | { |
| | 1 | 60 | | return cycleElem!; // Cycle detected |
| | | 61 | | } |
| | | 62 | | |
| | | 63 | | try |
| | | 64 | | { |
| | 43 | 65 | | return ObjectToXml(name, value, depth, visited); |
| | | 66 | | } |
| | | 67 | | finally |
| | | 68 | | { |
| | 43 | 69 | | if (needsCycleTracking && visited is not null) |
| | | 70 | | { |
| | 43 | 71 | | _ = visited.Remove(value); |
| | | 72 | | } |
| | 43 | 73 | | } |
| | 43 | 74 | | } |
| | | 75 | | |
| | | 76 | | /// <summary> |
| | | 77 | | /// Handles depth guard, null, enums, primitives, simple temporal types, dictionaries & enumerables. |
| | | 78 | | /// </summary> |
| | | 79 | | /// <param name="name">The name of the XML element.</param> |
| | | 80 | | /// <param name="value">The object to convert to XML.</param> |
| | | 81 | | /// <param name="depth">The current recursion depth.</param> |
| | | 82 | | /// <param name="element">The resulting XML element if handled; otherwise, null.</param> |
| | | 83 | | /// <param name="visited">Per-call set used for cycle detection (reference types only).</param> |
| | | 84 | | /// <returns><c>true</c> if the value was handled; otherwise, <c>false</c>.</returns> |
| | | 85 | | private static bool TryHandleTerminal(string name, object? value, int depth, ref HashSet<object>? visited, out XElem |
| | | 86 | | { |
| | | 87 | | // Depth guard handled below. |
| | 112 | 88 | | if (depth >= MaxDepth) |
| | | 89 | | { |
| | 2 | 90 | | element = new XElement(name, new XAttribute("warning", "MaxDepthExceeded")); |
| | 2 | 91 | | return true; |
| | | 92 | | } |
| | | 93 | | |
| | | 94 | | // Null |
| | 110 | 95 | | if (value is null) |
| | | 96 | | { |
| | 6 | 97 | | element = new XElement(name, new XAttribute(xsi + "nil", true)); |
| | 6 | 98 | | return true; |
| | | 99 | | } |
| | | 100 | | |
| | 104 | 101 | | var type = value.GetType(); |
| | | 102 | | |
| | | 103 | | // Enum |
| | 104 | 104 | | if (type.IsEnum) |
| | | 105 | | { |
| | 0 | 106 | | element = new XElement(name, value.ToString()); |
| | 0 | 107 | | return true; |
| | | 108 | | } |
| | | 109 | | |
| | | 110 | | // Primitive / simple |
| | 104 | 111 | | if (IsSimple(value)) |
| | | 112 | | { |
| | 58 | 113 | | element = new XElement(name, value); |
| | 58 | 114 | | return true; |
| | | 115 | | } |
| | | 116 | | |
| | | 117 | | // DateTimeOffset / TimeSpan (already covered by IsSimple for DateTimeOffset/TimeSpan? DateTimeOffset yes, TimeS |
| | 46 | 118 | | if (value is DateTimeOffset dto) |
| | | 119 | | { |
| | 0 | 120 | | element = new XElement(name, dto.ToString("O")); |
| | 0 | 121 | | return true; |
| | | 122 | | } |
| | 46 | 123 | | if (value is TimeSpan ts) |
| | | 124 | | { |
| | 0 | 125 | | element = new XElement(name, ts.ToString()); |
| | 0 | 126 | | return true; |
| | | 127 | | } |
| | | 128 | | |
| | | 129 | | // IDictionary |
| | 46 | 130 | | if (value is IDictionary dict) |
| | | 131 | | { |
| | 1 | 132 | | element = DictionaryToXml(name, dict, depth, visited); |
| | 1 | 133 | | return true; |
| | | 134 | | } |
| | | 135 | | |
| | | 136 | | // IEnumerable |
| | 45 | 137 | | if (value is IEnumerable enumerable) |
| | | 138 | | { |
| | 1 | 139 | | element = EnumerableToXml(name, enumerable, depth, visited); |
| | 1 | 140 | | return true; |
| | | 141 | | } |
| | | 142 | | |
| | 44 | 143 | | element = null!; |
| | 44 | 144 | | return false; |
| | | 145 | | } |
| | | 146 | | |
| | | 147 | | /// <summary> |
| | | 148 | | /// Enters cycle tracking for the specified object. Returns false if a cycle is detected. |
| | | 149 | | /// </summary> |
| | | 150 | | /// <param name="value">The object to track.</param> |
| | | 151 | | /// <param name="cycleElement">The resulting XML element if a cycle is detected; otherwise, null.</param> |
| | | 152 | | /// <returns><c>true</c> if the object is successfully tracked; otherwise, <c>false</c>.</returns> |
| | | 153 | | /// <param name="visited">Per-call set of visited objects (created lazily).</param> |
| | | 154 | | private static bool EnterCycle(object value, ref HashSet<object>? visited, out XElement? cycleElement) |
| | | 155 | | { |
| | 44 | 156 | | visited ??= new HashSet<object>(ReferenceEqualityComparer.Instance); |
| | 44 | 157 | | if (!visited.Add(value)) |
| | | 158 | | { |
| | 1 | 159 | | cycleElement = new XElement("Object", new XAttribute("warning", "CycleDetected")); |
| | 1 | 160 | | return false; |
| | | 161 | | } |
| | 43 | 162 | | cycleElement = null; |
| | 43 | 163 | | return true; |
| | | 164 | | } |
| | | 165 | | |
| | | 166 | | /// <summary> |
| | | 167 | | /// Determines whether the specified object is a simple type (primitive, string, DateTime, Guid, or decimal). |
| | | 168 | | /// </summary> |
| | | 169 | | /// <param name="value">The object to check.</param> |
| | | 170 | | /// <returns><c>true</c> if the object is a simple type; otherwise, <c>false</c>.</returns> |
| | | 171 | | private static bool IsSimple(object value) |
| | | 172 | | { |
| | 104 | 173 | | var type = value.GetType(); |
| | 104 | 174 | | return type.IsPrimitive |
| | 104 | 175 | | || value is string |
| | 104 | 176 | | || value is DateTime or DateTimeOffset |
| | 104 | 177 | | || value is Guid |
| | 104 | 178 | | || value is decimal |
| | 104 | 179 | | || value is TimeSpan; |
| | | 180 | | } |
| | | 181 | | |
| | | 182 | | /// <summary>Converts a dictionary to an XML element (recursive).</summary> |
| | | 183 | | /// <param name="name">Element name for the dictionary.</param> |
| | | 184 | | /// <param name="dict">Dictionary to serialize.</param> |
| | | 185 | | /// <param name="depth">Current recursion depth (guarded).</param> |
| | | 186 | | /// <param name="visited">Per-call set used for cycle detection.</param> |
| | | 187 | | private static XElement DictionaryToXml(string name, IDictionary dict, int depth, HashSet<object>? visited) |
| | | 188 | | { |
| | 1 | 189 | | var elem = new XElement(name); |
| | 6 | 190 | | foreach (DictionaryEntry entry in dict) |
| | | 191 | | { |
| | 2 | 192 | | var key = SanitizeName(entry.Key?.ToString() ?? "Key"); |
| | 2 | 193 | | elem.Add(ToXmlInternal(key, entry.Value, depth + 1, visited)); |
| | | 194 | | } |
| | 1 | 195 | | return elem; |
| | | 196 | | } |
| | | 197 | | /// <summary>Converts an enumerable to an XML element; each item becomes <Item/>.</summary> |
| | | 198 | | /// <param name="name">Element name for the collection.</param> |
| | | 199 | | /// <param name="enumerable">Sequence to serialize.</param> |
| | | 200 | | /// <param name="depth">Current recursion depth (guarded).</param> |
| | | 201 | | /// <param name="visited">Per-call set used for cycle detection.</param> |
| | | 202 | | private static XElement EnumerableToXml(string name, IEnumerable enumerable, int depth, HashSet<object>? visited) |
| | | 203 | | { |
| | 1 | 204 | | var elem = new XElement(name); |
| | 6 | 205 | | foreach (var item in enumerable) |
| | | 206 | | { |
| | 2 | 207 | | elem.Add(ToXmlInternal("Item", item, depth + 1, visited)); |
| | | 208 | | } |
| | 1 | 209 | | return elem; |
| | | 210 | | } |
| | | 211 | | |
| | | 212 | | /// <summary>Reflects an object's public instance properties into XML.</summary> |
| | | 213 | | /// <param name="name">Element name for the object.</param> |
| | | 214 | | /// <param name="value">Object instance to serialize.</param> |
| | | 215 | | /// <param name="depth">Current recursion depth (guarded).</param> |
| | | 216 | | /// <param name="visited">Per-call set used for cycle detection.</param> |
| | | 217 | | private static XElement ObjectToXml(string name, object value, int depth, HashSet<object>? visited) |
| | | 218 | | { |
| | 43 | 219 | | var objElem = new XElement(name); |
| | 43 | 220 | | var type = value.GetType(); |
| | 276 | 221 | | foreach (var prop in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) |
| | | 222 | | { |
| | 95 | 223 | | if (prop.GetIndexParameters().Length > 0) |
| | | 224 | | { |
| | | 225 | | continue; // skip indexers |
| | | 226 | | } |
| | | 227 | | object? propVal; |
| | | 228 | | try |
| | | 229 | | { |
| | 95 | 230 | | propVal = prop.GetValue(value); |
| | 95 | 231 | | } |
| | 0 | 232 | | catch |
| | | 233 | | { |
| | 0 | 234 | | continue; // skip unreadable props |
| | | 235 | | } |
| | 95 | 236 | | var childName = SanitizeName(prop.Name); |
| | 95 | 237 | | objElem.Add(ToXmlInternal(childName, propVal, depth + 1, visited)); |
| | | 238 | | } |
| | 43 | 239 | | return objElem; |
| | | 240 | | } |
| | | 241 | | |
| | | 242 | | private static string SanitizeName(string raw) |
| | | 243 | | { |
| | 110 | 244 | | if (string.IsNullOrWhiteSpace(raw)) |
| | | 245 | | { |
| | 0 | 246 | | return "Element"; |
| | | 247 | | } |
| | | 248 | | // XML element names must start with letter or underscore; replace invalid chars with '_' |
| | 110 | 249 | | var sb = new System.Text.StringBuilder(raw.Length); |
| | 1212 | 250 | | for (var i = 0; i < raw.Length; i++) |
| | | 251 | | { |
| | 496 | 252 | | var ch = raw[i]; |
| | 496 | 253 | | var valid = i == 0 |
| | 496 | 254 | | ? (char.IsLetter(ch) || ch == '_') |
| | 496 | 255 | | : (char.IsLetterOrDigit(ch) || ch == '_' || ch == '-' || ch == '.'); |
| | 496 | 256 | | _ = sb.Append(valid ? ch : '_'); |
| | | 257 | | } |
| | 110 | 258 | | return sb.ToString(); |
| | | 259 | | } |
| | | 260 | | |
| | | 261 | | private sealed class ReferenceEqualityComparer : IEqualityComparer<object> |
| | | 262 | | { |
| | 1 | 263 | | public static readonly ReferenceEqualityComparer Instance = new(); |
| | 44 | 264 | | public new bool Equals(object? x, object? y) => ReferenceEquals(x, y); |
| | 87 | 265 | | public int GetHashCode(object obj) => System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj); |
| | | 266 | | } |
| | | 267 | | |
| | | 268 | | /// <summary> |
| | | 269 | | /// Converts an <see cref="XElement"/> into a <see cref="Hashtable"/>. |
| | | 270 | | /// Nested elements become nested Hashtables; repeated elements become lists. |
| | | 271 | | /// Attributes are stored as keys prefixed with "@", xsi:nil="true" becomes <c>null</c>. |
| | | 272 | | /// </summary> |
| | | 273 | | /// <param name="element">The XML element to convert.</param> |
| | | 274 | | /// <returns>A Hashtable representation of the XML element.</returns> |
| | | 275 | | public static Hashtable ToHashtable(XElement element) |
| | | 276 | | { |
| | 17 | 277 | | var table = new Hashtable(); |
| | | 278 | | |
| | | 279 | | // Handle attributes (as @AttributeName) |
| | 40 | 280 | | foreach (var attr in element.Attributes()) |
| | | 281 | | { |
| | 4 | 282 | | if (attr.Name.NamespaceName == xsi.NamespaceName && attr.Name.LocalName == "nil" && attr.Value == "true") |
| | | 283 | | { |
| | 2 | 284 | | return new Hashtable { [element.Name.LocalName] = null! }; |
| | | 285 | | } |
| | 2 | 286 | | table["@" + attr.Name.LocalName] = attr.Value; |
| | | 287 | | } |
| | | 288 | | |
| | | 289 | | // If element has no children → treat as value |
| | 15 | 290 | | if (!element.HasElements) |
| | | 291 | | { |
| | 10 | 292 | | if (!string.IsNullOrWhiteSpace(element.Value)) |
| | | 293 | | { |
| | 9 | 294 | | table[element.Name.LocalName] = element.Value; |
| | | 295 | | } |
| | 10 | 296 | | return table; |
| | | 297 | | } |
| | | 298 | | |
| | | 299 | | // Otherwise recurse into children |
| | 5 | 300 | | var childMap = new Hashtable(); |
| | 28 | 301 | | foreach (var child in element.Elements()) |
| | | 302 | | { |
| | 9 | 303 | | var childKey = child.Name.LocalName; |
| | 9 | 304 | | var childValue = ToHashtable(child); |
| | | 305 | | |
| | 9 | 306 | | if (childMap.ContainsKey(childKey)) |
| | | 307 | | { |
| | | 308 | | // Already exists → convert to List (allowing null values) |
| | 3 | 309 | | if (childMap[childKey] is List<object?> list) |
| | | 310 | | { |
| | 1 | 311 | | list.Add(childValue[childKey]); |
| | | 312 | | } |
| | | 313 | | else |
| | | 314 | | { |
| | 2 | 315 | | childMap[childKey] = new List<object?> |
| | 2 | 316 | | { |
| | 2 | 317 | | childMap[childKey], |
| | 2 | 318 | | childValue[childKey] |
| | 2 | 319 | | }; |
| | | 320 | | } |
| | | 321 | | } |
| | | 322 | | else |
| | | 323 | | { |
| | 6 | 324 | | childMap[childKey] = childValue[childKey]; |
| | | 325 | | } |
| | | 326 | | } |
| | | 327 | | |
| | 5 | 328 | | table[element.Name.LocalName] = childMap; |
| | 5 | 329 | | return table; |
| | 2 | 330 | | } |
| | | 331 | | } |