CSharp · Console
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RestSharp.Deserializers;
using RestSharp.Extensions;
using RestSharp;
using System.Diagnostics;
using RestSharp.Serializers;
using System.Xml.Linq;
using System.Xml.Serialization;
// https://stackoverflow.com/questions/47023764/deserialize-xml-in-c-sharp#47023764
public class Vehicle
{
public bool Found { get; set; }
public string Description { get; set; }
public string BuildDate { get; set; }
public string ModelYear { get; set; }
public List<Option> OptionList { get; set; }
}
public class Option
{
public string Code { get; set; }
public string Value { get; set; }
}
class TestClass
{
public static void Test()
{
var xml = GetXml();
RestSharp.RestResponse response = new RestSharp.RestResponse();
response.Content = xml;
response.ContentType = "text/xml";
var xmlDeserializer = new RestSharp.Deserializers.XmlDeserializer();
var results = xmlDeserializer.Deserialize<Vehicle>(response);
Console.WriteLine("\nTesting {0}, deserialization result:", xmlDeserializer.GetType());
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(results, Newtonsoft.Json.Formatting.Indented));
Assert.IsTrue(XElement.Parse(xml).Elements("optionList").Elements("option").Select(e => e.Value).SequenceEqual(results.OptionList.Select(o => o.Value)));
Console.WriteLine("Descriptions deserialized successfully.");
}
static string GetXml()
{
var xml = @"<vehicle found=""1"">
<description>VehicleDescText</description>
<buildDate>2000-11-20</buildDate>
<modelYear>2001</modelYear>
<optionList>
<option code=""UH8"">OptionDesc1</option>
<option code=""UH8"">OptionDesc2</option>
</optionList>
</vehicle>";
return xml;
}
}
public class AssertionFailedException : System.Exception
{
public AssertionFailedException() : base() { }
public AssertionFailedException(string s) : base(s) { }
}
public static class Assert
{
public static void IsTrue(bool value)
{
IsTrue(value, "failed");
}
public static void IsTrue(bool value, string message)
{
if (value == false)
throw new AssertionFailedException(message ?? "failed");
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Environment version: " + Environment.Version);
Console.WriteLine();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Exception thrown: ");
Console.WriteLine(ex);
throw;
}
}
}