1

I have a situation where I need to deserialise XML to a model, and then map that model using automapper to another model. The issue is that the XML is structured in such a way that the element names match the properties in the model that I'm initially trying to map to...but for the most part the actual data is in an attribute called 'Val' in the element e.g.:

<Vehicle>
      <RegNo Val="ABC123A"/>
</Vehicle>

Now the normal way to do such a mapping, I think, would be (I've not bothered with a root element!):


[XmlElement("Vehicle")]
public class Vehicle {
[XmlElement("Regno")]
public Regno Regno { get; set; }
}


public class Regno {
    [XmlAttribute]
    public string Val {get;set;}    
}

That would allow the XML to map to the 'holding' object, but it does mean that rather than referencing a string called Regno, making the mapping to the second model fairly simple, I would have to reference Regno.Val. This doesn't sound a lot, but there's a lot of elements in the XML, and some of them use differently named attributes and the like. What I'd really like to do is define all the heavy lifting in the holding model defintion, using XMLAttributes etc. along the lines of:

[XmlElement("Vehicle")]
public class Vehicle {
[XmlElement("Regno.Val")]
public string Regno { get; set; }
}

So almost like being able to supply a path, or qualified value name. Effectively, moving the data one place up the hierarchy if that makes sense!

Is it possible to do this? I mean I could set up bespoke mappings in the automapper for moving from the holding model to the main model, but it would simpler if I could just go through the properties in the assemblies for each model and map from one to the other. Also given that not all the attributes are called 'Val', it could make things a bit messy, and it would be better if I could deal with it at the outset at the time the data is deserialised.

Edit: Should have added that I've tried the 'path' approach and couldn't get it to work, so I should have asked 'Am I doing it wrong?'

AmFearLiathMor
  • 183
  • 1
  • 11
  • Does this answer your question? [Serialize Property as Xml Attribute in Element](https://stackoverflow.com/questions/11330643/serialize-property-as-xml-attribute-in-element) – Innat3 Jan 14 '20 at 09:51
  • Hi - thanks for the suggestion, but unfortunately, I think what they are doing in that link is very similar to what I initially put above. I was trying to avoid having to reference the 'val' or 'value' to access the data for my automapping, although it has given me an idea for a slightly contrived way around the issue! – AmFearLiathMor Jan 14 '20 at 11:09

0 Answers0