簡體   English   中英

使用Automapper自動將所有XML標簽映射到類

[英]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>

上課:

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找不到對應的節點,則會引發異常。 在這種情況下,您可能會決定做其他事情。 例如,您可能決定返回null,空字符串或某些默認值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM