Reputation: 618
I've been supplied supplied an XML format that I'm really struggling to deserialize:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<data version='1'>
<id>1</id>
<property name='firstName'>John</property>
<property name='lastName'>Smith</property>
</data>
My issue is when it comes to the "property" element. I've never had to handle something like that, so I'm not sure how my class should be structured. I'd usually go with:
public class data
{
public string id { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
}
And then deserialize like so:
var recordSerializer = new XmlSerializer(typeof(data));
var myData = (data)recordSerializer.Deserialize(reader);
I did try creating a custom "property" class, but I couldn't figure out where to go from there:
public class property
{
public string name { get; set; }
public string value { get; set; }
}
Upvotes: 1
Views: 291
Reputation: 452
You can do this
public class data
{
public string id { get; set; }
[XmlElement(ElementName = "property")]
public List<property> lista { get; set; }
}
public class property
{
[XmlAttribute("name")]
public string name { get; set; }
[XmlText( typeof(string))]
public string value { get; set; }
}
without using a list would have to add the namespace in xml to differentiate the properties
Upvotes: 1
Reputation: 756
Give your data class an array of the propertyclass
public class data
{
public string id { get; set; }
[XmlElement("property")]
public property[] Properties { get; set; }
}
Upvotes: 0