使用 Automapper 自动将所有 XML 标签映射到 class

Automatically map all XML tags to class using Automapper

如何映射此 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>

到class:

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

你可以这样做:

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 中找不到相应的节点,我将抛出异常。在这种情况下,您可能决定做其他事情。例如,您可能决定 return null、空字符串或某个默认值。