Custom XML serialization - Include class name

本秂侑毒 提交于 2019-12-23 11:57:10

问题


I'm after 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'm wanting the inner body to contain the class name <ExampleObject>.

I use generics as I need to have different Message Body's, I serialize with the code:

var obj = new Message<ExampleObject>
{
    Version = "1.0",
    Body = example
};

var serializer2 = new XmlSerializer(typeof (Message<ExampleObject>));

回答1:


As @Marc Gravell suggested 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);


来源:https://stackoverflow.com/questions/8853082/custom-xml-serialization-include-class-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!