Stu Whyte
Stu Whyte

Reputation: 768

C# XML Serialisation of Object that has an Object field without namespaces

I am trying to serialize an Object into XML which has an 'Object' field. I want to achieve XML with no namespaces or attributes. I am able to remove the namespace of the root element, however, the Object element remains having a namespace.

My Object to serialize;

public class Message {
        public String Metadata { get; set; }
        public Object Payload { get; set; }


        public Message() {
        }

        public Message(String Metadata, Object Payload) {
            this.Metadata = Metadata;
            this.Payload = Payload;
        }
    }

How I serialize;

var s = new System.Xml.Serialization.XmlSerializer(typeof(Message));
var ns = new System.Xml.Serialization.XmlSerializerNamespaces();
ns.Add(String.Empty, String.Empty);
StringWriter writer = new StringWriter();
s.Serialize(writer, payload, ns);
writer.Close();

My output:

<Message>
  <Metadata>myMetadata</Metadata>
  <Payload xmlns:q1="http://www.w3.org/2001/XMLSchema" d2p1:type="q1:string" xmlns:d2p1="http://www.w3.org/2001/XMLSchema-instance">myPayload</Payload>
</Message>

My ideal output:

<Message>
  <Metadata>myMetadata</Metadata>
  <Payload>myPayload</Payload>
</Message>

I am a Java developer, and this is my first day doing C#! So apologies if I am missing anything obvious.

(My main goal is to end up having the following output)

<Message>
  <Metadata>myMetadata</Metadata>
  <Payload class="aClass">myPayload</Payload>
</Message>

But I can look into that myself once I have found a solution to the above problem!

Upvotes: 2

Views: 490

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292355

The type attribute is necessary in order to be able to deserialize the Payload property; if the serializer doesn't know the type of the content, how can it deserialize it?

Normally the namespaces are added to the root element, but you explicitly prevented that by specifying a XmlSerializerNamespaces with an empty mapping, so the namespace is added on the Payload element instead.

If you use XmlSerializer, the best you can do is this:

<Message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Metadata>myMetadata</Metadata>
  <Payload xsi:type="xsd:string">myPayload</Payload>
</Message>

Now, you could of course generate the XML manually, without any namespace, but then you would need some way of knowing the type of Payload for deserialization.

Upvotes: 3

Related Questions