反序列化字符串

时间:2011-08-08 09:02:34

标签: c# xml serialization

目前我正在使用此代码反序列化文件

            StreamReader str = new StreamReader(reply);
            System.Xml.Serialization.XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(typeof(imginfo));
            imginfo res = (imginfo)xSerializer.Deserialize(str);

如果reply是字符串而不是xml文件的路径,我应该如何修改代码?

2 个答案:

答案 0 :(得分:2)

基本上,您使用XmlReader链接到StringReader

imginfo res;
using(var sr = new StringReader(xml)) // "xml" is our string containing xml
using(var xr = XmlReader.Create(sr)) {
    res = (imginfo)xSerializer.Deserialize(xr);
}
//... use "res"

或安德斯指出:

imginfo res;
using(var sr = new StringReader(xml)) // "xml" is our string containing xml
    res = (imginfo)xSerializer.Deserialize(sr);
}
//... use "res"

答案 1 :(得分:1)

使用StringReader代替StreamReader。无需其他更改。