Data Contract Serializer - How to omit the outer element of a collection

前端 未结 3 741
星月不相逢
星月不相逢 2020-11-28 16:13

How do I serialize a list without the outer element using the Data Contract Serializer? I am using .Net 3.5. I have a class that contains a list, amongst

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 16:33

    Use a collection data contract:

        [CollectionDataContract(Name = "MyClass", ItemName = "Parameter")]
        public class ParameterList : List
        {
    
        }
    

    Here is the actual code:

    public class TestSerialize
    {
        [DataContract(Name = "Parameter")]
        public struct Parameter
        {
            [DataMember(Name = "ValueName")] string ValueName;
            [DataMember(Name = "Value")] int Value;
            public Parameter(string ValueName, int Value)
            {
                this.ValueName = ValueName;
                this.Value = Value;
            }
        }
    
        [CollectionDataContract(Name = "MyClass", ItemName = "Parameter")]
        public class ParameterList : List
        {
    
        }
    
    
        public string Serialize(ParameterList plist)
        {
            var serializer = new DataContractSerializer(plist.GetType());
            var output = new StringBuilder();
            var xmlWriter = XmlWriter.Create(output);
    
            serializer.WriteObject(xmlWriter, plist);
            xmlWriter.Close();
    
            return output.ToString();
        }
    
    
        public void Serialize_produces_2Levels_of_xml()
        {
            ParameterList p = new ParameterList
            {
                new Parameter("First", 1),
                new Parameter("Second", 2),
            };
    
            var xml = Serialize(p);
        }
    }
    

    if you run this you will get the following XML:

    
    
        
            1
            First
        
        
            2
            Second
        
    
    

提交回复
热议问题