Skip to content

Instantly share code, notes, and snippets.

@beginor
Created January 12, 2022 08:16
Show Gist options
  • Save beginor/9603ca52a1c60696afaff0161fbb4e27 to your computer and use it in GitHub Desktop.
Save beginor/9603ca52a1c60696afaff0161fbb4e27 to your computer and use it in GitHub Desktop.
using System.Xml;
using AutoMapper;
namespace AutoMapperTest;
public class Entity {
public XmlDocument Statement { get; set; }
}
public class Model {
public string Statement { get; set; }
}
public class StringToXmlConverter : IValueConverter<string, XmlDocument> {
public XmlDocument Convert(string sourceMember, ResolutionContext context) {
var xmlDoc = new XmlDocument();
if (!string.IsNullOrEmpty(sourceMember)) {
xmlDoc.LoadXml(sourceMember);
}
return xmlDoc;
}
}
public class Program {
public static void Main(string[] args) {
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Entity, Model>()
.ForMember(d => d.Statement, opt => opt.MapFrom(s => s.Statement.OuterXml))
.ReverseMap()
// .ForMember(d => d.Statement, opt => opt.MapFrom(s => StringToXmlDoc(s.Statement)));
// .ForMember(
// d => d.Statement,
// opt => opt.ConvertUsing(new StringToXmlConverter(), s => s.Statement)
// );
.ForMember(
dest => dest.Statement,
map => map.Ignore()
).AfterMap(
(apiModel, api) => api.Statement = StringToXmlDoc(apiModel.Statement)
);
});
config.AssertConfigurationIsValid();
config.CompileMappings();
var mapper = config.CreateMapper();
var entity = new Entity {
Statement = new XmlDocument()
};
entity.Statement.LoadXml("<abc>xxx</abc>");
var model = mapper.Map<Model>(entity);
Console.WriteLine(model.Statement);
entity = mapper.Map<Entity>(model);
Console.WriteLine(entity.Statement);
}
private static XmlDocument StringToXmlDoc(string xml) {
var xmlDoc = new XmlDocument();
if (!string.IsNullOrEmpty(xml)) {
xmlDoc.LoadXml(xml);
}
return xmlDoc;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment