1.0

Custom XML Serialization - Including Class Name

I get the following XML serialization output:

<?xml version="1.0"?> <Message> <Version>1.0</Version> <Body> <ExampleObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <EmampleOne>Hello!</EmampleOne> </ExampleObject> </Body> </Message> 

I have the following classes:

 [Serializable] public class Message<T> { public string Version { get; set; } public T Body { get; set; } } [Serializable] public class ExampleObject { public string EmampleOne { get; set; } } 

If I serialize them separately, I get:

 <?xml version="1.0"?> <Message> <Version>1.0</Version> <Body> <EmampleOne>Hello!</EmampleOne> </Body> </Message> 

and

 <?xml version="1.0"?> <ExampleObject> <EmampleOne>Hello!</EmampleOne> </ExampleObject> 

So, as shown above, I want the inner body to contain the class name <ExampleObject> .

I use generics, since I need to have different message bodies, I serialize the code:

 var obj = new Message<ExampleObject> { Version = "1.0", Body = example }; var serializer2 = new XmlSerializer(typeof (Message<ExampleObject>)); 
+4
source share
1 answer

As @Marc Gravell explained in his comment, you can use XmlAttributeOverrides :

 var xmlOverrides = new XmlAttributeOverrides(); var attributes = new XmlAttributes(); attributes.XmlElements .Add(new XmlElementAttribute("ExampleObject", typeof (ExampleObject))); xmlOverrides.Add(typeof(Message<ExampleObject>), "Body", attributes); var serializer2 = new XmlSerializer(typeof(Message<ExampleObject>), xmlOverrides); 
+3
source

Source: https://habr.com/ru/post/905809/


All Articles