使用Automapper自动将所有XML标记映射到类

本文关键字:映射 XML Automapper 使用 | 更新日期: 2023-09-27 18:18:04

如何映射XmlDocument 的每个TAG标记,而不显式指示所有成员映射:

<?xml version="1.0" encoding="UTF-8"?>
<RESULT>
  <TAG ID="foo">Hello</TAG>
  <TAG ID="bar">World</TAG>
  ... (huge amount of tags)
<RESULT>

类:

public class Result
{
    public string Foo { get; set; }
    public string Bar { get; set; }
    ... (huge amount of properties)
}

使用Automapper自动将所有XML标记映射到类

你可以这样做:

AutoMapper.Mapper.CreateMap<XmlDocument,Result>()
    .ForAllMembers(opt => opt.ResolveUsing(res =>
    {
        XmlDocument document = (XmlDocument)res.Context.SourceValue;
        var node = document
            .DocumentElement
            .ChildNodes
            .OfType<XmlElement>()
            .FirstOrDefault(
                element =>
                    element
                    .GetAttribute("ID")
                    .Equals(res.Context.MemberName, StringComparison.OrdinalIgnoreCase));
        if (node == null)
            throw new Exception("Could not find a corresponding node in the XML document");
        return node.InnerText;
    }));

请注意,您可以决定使用不同的方法来查找XmlDocument内部的适当节点。例如,您可能决定使用XPath。

还请注意,如果在XmlDocument中没有找到相应的节点,我将抛出异常。在这种情况下,您可能会决定做其他事情。例如,您可能决定返回null、空字符串或某些默认值。