If I have a xml file that looks like
<Foo>
<Name>Some Data</Name>
<Bar_Data>Other Data</Bar_Data>
<Bar_MoreData>More Data</Bar_MoreData>
</Foo>
And I want to turn it in to a C# class that looks like
public class Foo
{
public string Name {get; set; }
public Bar Bar { get; set; }
}
public class Bar
{
public string Data { get; set; }
public string MoreData { get; set; }
}
Is there any way to accomplish this with just simple data annotations (XmlRoot
, XmlElement
, etc.) or is my only option to implement IXmlSerializable
?
EDIT: Note, I only ever need to deserialize the data. I get the XML from a 3rd party source and I do not need to ever serialize Foo
back in to XML (if that makes it easier).
One option is to use XmlAnyElementAttribute as below:
When XmlSerializer does not recognize an element it adds it to property of type XmlElement[] marked by XmlAnyElementAttribute. That is where you can process Bar properties. I used reflection there to show the idea.
Another option is to deserialize twice and connect Bar with Foo:
Yet another option with no intrusion to classes being deserialized:
and if double deserialization or reflection is problematic performance wise, then you could create a surrogate proxy class: