gpt4 book ai didi

c# - 从字符串而不是 TextReader 反序列化

转载 作者:IT王子 更新时间:2023-10-29 03:33:37 27 4
gpt4 key购买 nike

我想更改我的代码:

string path = @"c:\Directory\test.xml";
XmlSerializer s = new XmlSerializer(typeof(Car));

TextReader r = new StreamReader(path);

Car car = (Car)s.Deserialize(r);
r.Close();

转换为将 XML 转换为字符串,然后将字符串转换为对象 Car 的代码。

这可能吗?

最佳答案

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>(this string objectData)
{
return (T)XmlDeserializeFromString(objectData, typeof(T));
}

public static object XmlDeserializeFromString(this string objectData, Type type)
{
var serializer = new XmlSerializer(type);
object result;

using (TextReader reader = new StringReader(objectData))
{
result = serializer.Deserialize(reader);
}

return result;
}

使用方法:

//Make XML
var settings = new ObjectCustomerSettings();
var xmlString = settings.XmlSerializeToString();

//Make Object
var settings = xmlString.XmlDeserializeFromString<ObjectCustomerSettings>();

关于c# - 从字符串而不是 TextReader 反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2347642/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com