我试图在下面的 C# 中反序列化一个相对简单的字符串。从 REST API 调用接收 XML 响应。来自 API 的响应存储在字符串中,因为 Spring.Rest 的内置转换器无法转换为 XMLDocument 对象,因此我正在尝试创建一个解决方法。
这是基本场景:
// Response from API
string emailData = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<email-address>xyz@gmail.com</email-address>";
// Code calling the conversion of the string
Console.WriteLine(
XmlConversion.XmlDeserializeFromString(emailData, typeof(Email)).ToString());
// Object being Deserialized into
public class Email
{
[System.Xml.Serialization.XmlElement("email-address")]
public string EmailAddress { get; set; }
}
// Conversion Class
public static class XmlConversion
{
public static string XmlSerializeToString(this object objectInstance)
{
var serializer = new XmlSerializer(objectInstance.GetType());
var sb = new StringBuilder();
using (TextWriter writer = new StringWriter(sb))
{
serializer.Serialize(writer, objectInstance);
}
return sb.ToString();
}
public static T XmlDeserializeFromString<T>(string objectData)
{
return (T)XmlDeserializeFromString(objectData, typeof(T));
}
public static object XmlDeserializeFromString(string objectData, Type type)
{
var serializer = new XmlSerializer(type);
object result;
using (TextReader reader = new StringReader(objectData))
{
result = serializer.Deserialize(reader);
}
return result;
}
}