Can I serialize Anonymous Types as xml?

后端 未结 7 2039
误落风尘
误落风尘 2020-11-27 04:48

I understood that anonymous types are marked private by the compiler and the properties are read-only. Is there a way to serialize them to xml (without deserialize) ? It wor

7条回答
  •  清酒与你
    2020-11-27 05:32

    The answer below handles IEnumerables in the way I needed and will turn this:

    new
    {
        Foo = new[]
        {
            new { Name = "One" },
            new { Name = "Two" },
        },
        Bar = new[]
        {
            new { Name = "Three" },
            new { Name = "Four" },
        },
    }
    

    into this:

    
        One
        Two
        Three
        Four
    
    

    So here you go, yet another variant of Matthew's answer:

    public static class Tools
    {
        private static readonly Type[] WriteTypes = new[] {
            typeof(string),
            typeof(Enum),
            typeof(DateTime), typeof(DateTime?),
            typeof(DateTimeOffset), typeof(DateTimeOffset?),
            typeof(int), typeof(int?),
            typeof(decimal), typeof(decimal?),
            typeof(Guid), typeof(Guid?),
        };
        public static bool IsSimpleType(this Type type)
        {
            return type.IsPrimitive || WriteTypes.Contains(type);
        }
        public static object ToXml(this object input)
        {
            return input.ToXml(null);
        }
        public static object ToXml(this object input, string element)
        {
            if (input == null)
                return null;
    
            if (string.IsNullOrEmpty(element))
                element = "object";
            element = XmlConvert.EncodeName(element);
            var ret = new XElement(element);
    
            if (input != null)
            {
                var type = input.GetType();
    
                if (input is IEnumerable && !type.IsSimpleType())
                {
                    var elements = (input as IEnumerable)
                        .Select(m => m.ToXml(element))
                        .ToArray();
    
                    return elements;
                }
                else
                {
                    var props = type.GetProperties();
    
                    var elements = from prop in props
                                   let name = XmlConvert.EncodeName(prop.Name)
                                   let val = prop.GetValue(input, null)
                                   let value = prop.PropertyType.IsSimpleType()
                                        ? new XElement(name, val)
                                        : val.ToXml(name)
                                   where value != null
                                   select value;
    
                    ret.Add(elements);
                }
            }
    
            return ret;
        }
    }
    
        

    提交回复
    热议问题