0

I know the basics of right way for map XML to strongly type objects but my received XML from service is different! my XMl is like this:

<Group>
    <Title>friends</Title>
    <Member>
        <Name>Omid</Name>
    </Member>
    <Member>
        <Name>Kourosh</Name>
    </Member>
<Group>

and my object is:

public class Group
{
    public string Title { get; set; };
    public ICollection<Member> Members { get; set; };
}

so when I try to map XElement (from XML) to Group then Members don't map :( whats the best way? changing XML? using specific config for AutoMapper? and how? thanks

Omid.Hanjani
  • 1,444
  • 2
  • 20
  • 29

2 Answers2

1

I finally read this useful article and change the _mapItems to this to solve my problem:

private static Func<XElement, string, List<XElement>> _mapItems =
    (src, elementName) =>
    src.Elements(elementName).ToList();
Omid.Hanjani
  • 1,444
  • 2
  • 20
  • 29
0

I read the same article and found that there was an XML format difference with my code. Mine was XML Element as compared to XML Attribute as suggested in article. Here is a StackOverflow link if someone needs more information.My XML was element based and not attribute based.

My XML was something like below and my challenge was to read multiple accounts

<consumer>
<id>XYZ</id>   
<birthDate>1990-05-22</birthDate>   
<accounts>
  <account>
    <id>123</id>
    <regdate>2014-05-22</regdate>        
  </account>
</accounts>

My code was the same as in article but I changed the MapItems function to following

private static readonly Func<XElement, string, string, List<XElement>> MapItems =
        (src, collectionName, elementName) =>
        (src.Element(collectionName) ?? new XElement(collectionName)).Elements(elementName).ToList(); 

When doing the mapping, I mapped it as follows

.ForMember(
                    dest => dest.Accounts,
                    opt => opt.MapFrom(src => MapItems(src, "accounts", "account")));
Community
  • 1
  • 1
Amit
  • 559
  • 5
  • 8