Created
February 22, 2022 15:33
-
-
Save rezanid/7ce38a4ae30fecf9ad52585155e422c3 to your computer and use it in GitHub Desktop.
Power Platform (Dynamics) FetchXml serializer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Xml.Linq; | |
namespace Playground | |
{ | |
public class FetchUtil | |
{ | |
private static readonly Type[] SimpleTypes = new Type[] { typeof(string), typeof(DateTime), typeof(Enum), typeof(decimal), typeof(Guid) }; | |
public static XElement ToXml(string rootName, object? x, XElement? root = null) | |
{ | |
if (x == null) { return new XElement(rootName); } | |
if (root == null) { root = new XElement(rootName); }; | |
if (SimpleTypes.Contains(x.GetType())) { return new XElement(rootName, x); } | |
var properties = x.GetType().GetProperties(); | |
foreach (var property in properties) | |
{ | |
var value = property.GetValue(x); | |
if (property.PropertyType.IsPrimitive || SimpleTypes.Contains(property.PropertyType)) | |
{ | |
root.SetAttributeValue(property.Name, value); | |
} | |
else if (value is Array array) | |
{ | |
for (int i = 0; i < array.Length; i++) | |
{ | |
root.Add(ToXml(property.Name, array.GetValue(i))); | |
} | |
} | |
else | |
{ | |
root.Add(value == null ? new XElement(property.Name) : ToXml(property.Name, value)); | |
} | |
} | |
return root; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment