问题描述
我需要将xml属性映射到c#属性.
I need to map a xml property to c# properties.
var src = new Source();
src.Id = 1;
src.Name = "Test";
src.Address = "<Country>MyCountry</Country><Prefecture>MyPrefecture</Prefecture><City>MyCity</City>";
class Source
{
public string ID{ get; set; }
public string Name{ get; set; }
public string Address{ get; set; }
}
Class Destination
{
public string ID{ get; set; }
public string Name{ get; set; }
public string Country { get; set;}
public string Prefecture { get; set;}
public string City { get; set;}
}
是否可以通过AutoMapper实现?
Is it possible to achieve it through AutoMapper?
推荐答案
您可以执行以下操作.考虑您的来源类型.
You can do the following. Considering your source type.
var src = new Source();
src.ID = 1;
src.Name = "Test";
src.Address = "<Country>MyCountry</Country><Prefecture>MyPrefecture</Prefecture><City>MyCity</City>";
由于您的源类型(src.Address)没有根元素,所以我们添加一个根元素并将xml解析为XDocument.
Since your source type (src.Address) doesn't have a root element, let's add one and parse the xml to a XDocument.
XDocument xdoc = new XDocument();
xdoc = XDocument.Parse($"<Root>{src.Address}</Root>");
现在在初始化Automapper时,您需要映射字段.
Now during Initializing of Automapper, you need to map fields.
Mapper.Initialize(cfg =>
cfg.CreateMap<XElement, Destination>()
.ForMember(dest => dest.Country, opt => opt.MapFrom(x=>x.Element(nameof(Destination.Country)).Value))
.ForMember(dest => dest.City, opt => opt.MapFrom(x => x.Element(nameof(Destination.City)).Value))
.ForMember(dest => dest.Prefecture, opt => opt.MapFrom(x => x.Element(nameof(Destination.Prefecture)).Value)));
现在您可以按以下步骤解决它.
Now you can resolve it as following.
Destination result = Mapper.Map<XElement, Destination>(xdoc.Root);
更新
您也可以为此目的使用ConstructUsing,这会将与Xml相关的代码隐藏在其他代码之外.
You can using ConstructUsing as well for the purpose, that would hide away the Xml related code away from your other codes.
var src = new Source();
src.ID = "1";
src.Name = "Test";
src.Address = "<Country>MyCountry</Country><Prefecture>MyPrefecture</Prefecture><City>MyCity</City>";
XDocument xdoc = new XDocument();
xdoc = XDocument.Parse($"<Root>{src.Address}</Root>");
Mapper.Initialize(cfg =>
cfg.CreateMap<Source, Destination>()
.ConstructUsing(x=>ConstructDestination(x))
);
ConstructDestination 定义为
static Destination ConstructDestination(Source src)
{
XDocument xdoc = new XDocument();
xdoc = XDocument.Parse($"<Root>{src.Address}</Root>");
return new Destination
{
Country = xdoc.Root.Element(nameof(Destination.Country)).Value,
City = xdoc.Root.Element(nameof(Destination.City)).Value,
Prefecture = xdoc.Root.Element(nameof(Destination.Prefecture)).Value,
};
}
您的客户端代码现在看起来更干净了.
Your client code looks much cleaner now.
Destination result = Mapper.Map<Source, Destination>(src);
这篇关于将xml字符串属性映射到C#属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!