我正在尝试在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;
}
}
答案 0 :(得分:2)
尝试将类的定义更改为:
[System.Xml.Serialization.XmlRoot("email-address")]
public class email
{
[System.Xml.Serialization.XmlText()]
public string emailAddress { get; set; }
}