How to add XmlInclude attribute dynamically

后端 未结 4 1703
青春惊慌失措
青春惊慌失措 2020-11-27 05:20

I have the following classes

[XmlRoot]
public class AList
{
   public List ListOfBs {get; set;}
}

public class B
{
   public string BaseProperty {g         


        
4条回答
  •  無奈伤痛
    2020-11-27 05:40

    Two options; the simplest (but giving odd xml) is:

    XmlSerializer ser = new XmlSerializer(typeof(AList),
        new Type[] {typeof(B), typeof(C)});
    

    With example output:

    
      
        
        
      
    
    

    The more elegant is:

    XmlAttributeOverrides aor = new XmlAttributeOverrides();
    XmlAttributes listAttribs = new XmlAttributes();
    listAttribs.XmlElements.Add(new XmlElementAttribute("b", typeof(B)));
    listAttribs.XmlElements.Add(new XmlElementAttribute("c", typeof(C)));
    aor.Add(typeof(AList), "ListOfBs", listAttribs);
    
    XmlSerializer ser = new XmlSerializer(typeof(AList), aor);
    

    With example output:

    
      
      
    
    

    In either case you must cache and re-use the ser instance; otherwise you will haemorrhage memory from dynamic compilation.

提交回复
热议问题