Skip to content

Instantly share code, notes, and snippets.

@rezanid
Created February 22, 2022 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rezanid/7ce38a4ae30fecf9ad52585155e422c3 to your computer and use it in GitHub Desktop.
Save rezanid/7ce38a4ae30fecf9ad52585155e422c3 to your computer and use it in GitHub Desktop.
Power Platform (Dynamics) FetchXml serializer
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