I have a web service that when called gives me an XML result in the following structure:
<returns>
<return>
<name>firstName</name>
<value>John</value>
</return>
<return>
<name>lastName</name>
<value>Doe</value>
</return>
<return>
<name>dateOfBirth</name>
<value>01-01-1900 00:00</value>
</return>
<return>
<name>address</name>
<value>100, Example Street</value>
</return>
</returns>
If I go to Visual Studio > Edit > Paste Special > Paste XML As Classes
I get the following code generated to me:
// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class returns
{
private returnsReturn[] returnField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("return")]
public returnsReturn[] @return
{
get
{
return this.returnField;
}
set
{
this.returnField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class returnsReturn
{
private string nameField;
private string valueField;
/// <remarks/>
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
/// <remarks/>
public string value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
However what I would like to do is have a model class in the following structure, and then have the XML deserialized into it:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public string Address { get; set; }
}
How can I achieve this while having the provided XML structure? I have worked with JSON deserialization in the past, and if the return of the web service was something in the lines of this I would have no problem:
[
{
"firstName": "John",
"lastName": "Doe",
"dateOfBirth": "01-01-1900 00:00",
"address": "100, Example Street"
}
]
Or even if it was a XML with the following structure:
<customers>
<customer>
<firstName>John</firstName>
<lastName>Doe</lastName>
<dateOfBirth>01-01-1900 00:00</dateOfBirth>
<address>100, Example Street</address>
</customer>
</customers>
But I don't know how to deal or deserialize a XML composed of "name" and "value" fields. How can I work with (deserialize into it's proper model) this kind of XML using C# and .NET Core?
Try this one, It's a console app and it's working well with a Deserialize method to read
xml
from a file path and map it into aPerson
POCO
class for youHi you can deserialize your XML by a using function something like below:
Call this function in your Person Class Constructor
However a good approach is to design your xml response to return something like below:
And then make your Person class Serializable that way you don't have to use the for loop and switch case to populate the values
Try code below. I reading xml from file put you can use any string input. :