Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. How to add XmlInclude attribute dynamically

How to add XmlInclude attribute dynamically

Scheduled Pinned Locked Moved C#
helptutorialquestion
1 Posts 1 Posters 2 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    Anindya Chatterjee
    wrote on last edited by
    #1

    I have the following classes

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

    public class B
    {
    public string BaseProperty {get; set;}
    }

    public class C : B
    {
    public string SomeProperty {get; set;}
    }

    public class Main
    {
    public static void Main(string[] args)
    {
    var aList = new AList();
    aList.ListOfBs = new List<B>();
    var c = new C { BaseProperty = "Base", SomeProperty = "Some" };
    aList.ListOfBs.Add(c);

        var type = typeof (AList);
        var serializer = new XmlSerializer(type);
        TextWriter w = new StringWriter();
        serializer.Serialize(w, aList);
    }    
    

    }

    Now when I try to run the code I got an InvalidOperationException at last line saying that The type XmlTest.C was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically. I know that adding a [XmlInclude(typeof(C))] attribute with [XmlRoot] would solve the problem. But I want to achieve it dynamically. Because in my project class C is not known prior to loading. Class C is being loaded as a plugin, so it is not possible for me to add XmlInclude attribute there. I tried also with

    TypeDescriptor.AddAttributes(typeof(AList), new[] { new XmlIncludeAttribute(c.GetType()) });

    before

    var type = typeof (AList);

    but no use. It is still giving the same exception. Does any one have any idea on how to achieve it?

    Regards, Anindya Chatterjee[^]

    1 Reply Last reply
    0
    Reply
    • Reply as topic
    Log in to reply
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes


    • Login

    • Don't have an account? Register

    • Login or register to search.
    • First post
      Last post
    0
    • Categories
    • Recent
    • Tags
    • Popular
    • World
    • Users
    • Groups