serializing a list of KeyValuePair to XML

前端 未结 2 424
闹比i
闹比i 2021-01-21 06:35

I am trying to serailize an Object into XML. Below is the XML format which I need.


  
    Key1
    <         


        
2条回答
  •  难免孤独
    2021-01-21 06:36

    You either need to make Parameter contain a list of the key values (by the way .net has several collections that do this for you such as Dictionary) e.g:

    public class Parameter{
      public Dictionary Values {get; set;}
    
      public Parameter()
      {
         Values = new Dictionary();
      }
    
      public void AddParameter(K key, V value)
      {
         Values.Add(key,value);
      }
    
      ...Other access methods here
    }
    

    Or in parameters just make it a list of key values or a dictionary:

    public class Parameters{
    
       public Dictionary Parameters {get; set;}
    
       public Parameters(){
           Parameters = new Dictionary();
       }
    }
    

    The second option is obviously the best one as the first is just re-inventing the .net Dictionary. There doesn't seem to be any benefit to the first.

    This is bread and butter stuff so if you don't really understand arrays and .net collections you should familiarize yourself with this area. Searching on stack overflow will give you all you need.

    You can use XmlElementAttribute.ElementName property to name the Parameters Dictionary as you like and it should produce the results you want although I would question why inside the parameters node you only want one parameter node?

提交回复
热议问题