XML Serialize dynamic object

后端 未结 1 1083
[愿得一人]
[愿得一人] 2020-12-05 00:46

I need to construct a set of dynamically created XML nodes from objects on the following format:


    My Name
    

        
相关标签:
1条回答
  • 2020-12-05 01:45
    [Serializable]
    public class DynamicSerializable : DynamicObject, ISerializable
    {
        private readonly Dictionary<string, object> dictionary = new Dictionary<string, object>();
    
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            dictionary[binder.Name] = value;
    
            return true;
        }
    
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            foreach (var kvp in dictionary)
            {
                info.AddValue(kvp.Key, kvp.Value);
            }
        }
    }
    
    [KnownType(typeof(DynamicSerializable))]
    [DataContract]
    public class Root
    {
        [DataMember]
        public string Name { get; set; }
    
        [DataMember]
        public dynamic DynamicValues { get; set; }
    }
    

    Output:

    <Program.Root xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://
    schemas.datacontract.org/2004/07/">
      <DynamicValues i:type="Program.DynamicSerializable">
        <DynamicValue1 xmlns:d3p1="http://www.w3.org/2001/XMLSchema" i:type="d3p1:st
    ring" xmlns="">Value 1</DynamicValue1>
        <DynamicValue2 xmlns:d3p1="http://www.w3.org/2001/XMLSchema" i:type="d3p1:st
    ring" xmlns="">Value 2</DynamicValue2>
      </DynamicValues>
      <Name>My Name</Name>
    </Program.Root>
    
    0 讨论(0)
提交回复
热议问题