当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Serialize an object to XML without using attributes

问题描述:

Is it possible to control XmlSerializer/DataContractSerializer behavior without specifying any serialization attributes?

To be more specific, I want to control the serialization (XmlIgnore, custom attribute name etc.), but without decorating my properties.

Use cases:

  • A large existing class, which I don't wish to pollute with serialization attributes
  • Serializing a class for which no source code is available
  • Switching from using XmlSerializer to DataContractSerializer to JSON without changing class code

For example, how would I serialize the following without uncommenting the attributes:

// [Serializable]

public MyClass

{

// [XmlIgnore] - The following property should not be serialized, without uncommenting this line

public int DontSerializeMeEvenThoughImPublic { get; set; }

// [XmlAttribute("another_name")] - should be serialized as 'another_name', not 'SerializeMeAsXmlAttribute'

public double SerializeMeAsXmlAttribute { get; set; }

// [DataMember] - should be included

private string IWantToBeSerializedButDontDecorateMeWithDataMember { get; set; }

}

网友答案:

You can't (do it elegantly).
The only way to modify the way the XmlSerializer serializes classes is by using attributes (by the way SerializableAttribute is not required). The DataContractSerializer is even worse.

One possible solution is to create intermediate classes for XML serialization/desrialization and use Automapper to copy the data between the "real" class and mediator. I've used this approach to keep the front end XML serialization concerns outside of my business logic data types.

网友答案:

Serialization via XmlSerializer should work without the attributes.

分享给朋友:
您可能感兴趣的文章:
随机阅读: