Search code examples
c#xmlxmlserializer

Exclude root node from xml using xmlserializer


I have a nested class which i use xmlserializer to convert it to xml.

public class RequestModel{

        [XmlElement("message", Namespace = "http://www.origostandards.com/schema/mtg/v2")]
        public Message message { get; set; }

        public RequestModel()
        {
            this.message = new Message();
        }
        public class Message
        {
           //other constructor here etc
        }
}

When it serializes it all compiles without issue however the output is as follows:

<RequestModel>
   <mtg:message>
   ...
   </mtg:message>
</RequestModel>

Is there a way to exclude the class name from serializing so that message would become the top node and the output would look like:

<mtg:message>
  ...
</mtg:message>

I have tried adding a Boolean for visibility of the node as well as things as XmlIgnore and XmlRoot but these attributes don't really fit with my solution.

Any help here would be appreciated.


Solution

  • Try different c# namespaces :

    namespace RequestA
    {
        public class RequestModel
        {
    
            [XmlElement("message", Namespace = "http://www.origostandards.com/schema/mtg/v2")]
            public Message.Message message { get; set; }
    
            public RequestModel()
            {
                this.message = new Message.Message();
            }
         }
    }
    namespace RequestB
    {
    
        public class RequestModel
        {
            [XmlElement("message", Namespace = "http://www.origostandards.com/schema/mtg/v2")]
            public Message.Message message { get; set; }
    
            public RequestModel()
            {
                this.message = new Message.Message();
            }
        }
    }
    namespace Message
    {
            public class Message
            {
                //other constructor here etc
            }
    
    }