如何将 XML 反序列化为 C# 中的对象? [复制]
Posted
技术标签:
【中文标题】如何将 XML 反序列化为 C# 中的对象? [复制]【英文标题】:How to deserialize XML into an object in C#? [duplicate] 【发布时间】:2020-08-01 08:51:26 【问题描述】:我需要读取 XML 并将其反序列化为 C# 中的对象。我使用 ToXmlFile(Object obj, string filePath) 函数的序列化部分创建了文件,如下所述。我在文件 test.xml 中创建了以下 XML:
<NYSE_Daily_Prices>
<stock_exchange>NYSE</stock_exchange>
<stock_symbol>ADI</stock_symbol>
<date>2000-01-03T00:00:00</date>
<stock_price_open>93.5</stock_price_open>
<stock_price_high>93.87</stock_price_high>
<stock_price_low>88</stock_price_low>
<stock_price_close>90.19</stock_price_close>
<stock_volume>3655600</stock_volume>
<stock_price_adj_close>39.97</stock_price_adj_close>
</NYSE_Daily_Prices>
<NYSE_Daily_Prices>
<stock_exchange>NYSE</stock_exchange>
<stock_symbol>ADI</stock_symbol>
<date>2000-01-04T00:00:00</date>
<stock_price_open>89.5</stock_price_open>
<stock_price_high>91.5</stock_price_high>
<stock_price_low>85.56</stock_price_low>
<stock_price_close>85.62</stock_price_close>
<stock_volume>2533200</stock_volume>
<stock_price_adj_close>37.95</stock_price_adj_close>
</NYSE_Daily_Prices>
<NYSE_Daily_Prices>
<stock_exchange>NYSE</stock_exchange>
<stock_symbol>ADI</stock_symbol>
<date>2000-01-05T00:00:00</date>
<stock_price_open>85.62</stock_price_open>
<stock_price_high>88.25</stock_price_high>
<stock_price_low>83.19</stock_price_low>
<stock_price_close>86.88</stock_price_close>
<stock_volume>3228000</stock_volume>
<stock_price_adj_close>38.51</stock_price_adj_close>
</NYSE_Daily_Prices>
这是我的对象:
public partial class NYSE_Daily_Prices
public string stock_exchange get; set;
public string stock_symbol get; set;
public System.DateTime date get; set;
public double stock_price_open get; set;
public double stock_price_high get; set;
public double stock_price_low get; set;
public double stock_price_close get; set;
public int stock_volume get; set;
public double stock_price_adj_close get; set;
这是序列化/反序列化的代码:
public static class XmlHelper
public static bool NewLineOnAttributes get; set;
/// <summary>
/// Serializes an object to an XML string, using the specified namespaces.
/// </summary>
public static string ToXml(object obj, XmlSerializerNamespaces ns)
Type T = obj.GetType();
var xs = new XmlSerializer(T);
var ws = new XmlWriterSettings Indent = true, NewLineOnAttributes = NewLineOnAttributes, OmitXmlDeclaration = true ;
var sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb, ws))
xs.Serialize(writer, obj, ns);
return sb.ToString();
/// <summary>
/// Serializes an object to an XML string.
/// </summary>
public static string ToXml(object obj)
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
return ToXml(obj, ns);
/// <summary>
/// Deserializes an object from an XML string.
/// </summary>
public static T FromXml<T>(string xml)
XmlSerializer xs = new XmlSerializer(typeof(T));
using (StringReader sr = new StringReader(xml))
return (T)xs.Deserialize(sr);
/// <summary>
/// Deserializes an object from an XML string, using the specified type name.
/// </summary>
public static object FromXml(string xml, string typeName)
Type T = Type.GetType(typeName);
XmlSerializer xs = new XmlSerializer(T);
using (StringReader sr = new StringReader(xml))
return xs.Deserialize(sr);
/// <summary>
/// Serializes an object to an XML file.
/// </summary>
public static void ToXmlFile(Object obj, string filePath)
var xs = new XmlSerializer(obj.GetType());
var ns = new XmlSerializerNamespaces();
var ws = new XmlWriterSettings Indent = true, NewLineOnAttributes = NewLineOnAttributes, OmitXmlDeclaration = true ;
ns.Add("", "");
using (XmlWriter writer = XmlWriter.Create(filePath, ws))
xs.Serialize(writer, obj);
/// <summary>
/// Deserializes an object from an XML file.
/// </summary>
public static T FromXmlFile<T>(string filePath)
StreamReader sr = new StreamReader(filePath);
try
var result = FromXml<T>(sr.ReadToEnd());
return result;
catch (Exception e)
throw new Exception("There was an error attempting to read the file " + filePath + "\n\n" + e.InnerException.Message);
finally
sr.Close();
以及我用来请求反序列化的代码:
string filePath = $@"C:\Users\dmast\Documents\Upskilled\C#\C# Programming Project\MoneyBMineWpfApp\MoneyBMineWpfApp\OfflineFilesXML\listRecentSearches.SelectedItem.ToString()";
NYSE_Daily_Prices result = XMLReadWrite.XmlHelper.FromXmlFile<NYSE_Daily_Prices>(filePath);
我不断收到捕获的异常:
catch (Exception e)
throw new Exception("There was an error attempting to read the file " + filePath + "\n\n" + e.InnerException.Message);
任何帮助将不胜感激:)
【问题讨论】:
当抛出一个新的异常(顺便说一下,它不应该是基本异常类)时,只需将实际异常作为内部异常。现在,内部异常说明了什么?throw
的参数包括 e.InnerException.Message
,但您没有显示该 throw 的输出,也没有编写代码来显示 e.Message
。
【参考方案1】:
戴维。你的代码对我来说看起来不错。我在本地试过。
您确定您提供了正确的文件路径吗?
我更改了一点 xml,因为我认为它应该有一个根元素。现在 .xml 文件如下所示:
<root>
<Prices>
<NYSE_Daily_Prices>
<stock_exchange>NYSE</stock_exchange>
<stock_symbol>ADI</stock_symbol>
<date>2000-01-03T00:00:00</date>
<stock_price_open>93.5</stock_price_open>
<stock_price_high>93.87</stock_price_high>
<stock_price_low>88</stock_price_low>
<stock_price_close>90.19</stock_price_close>
<stock_volume>3655600</stock_volume>
<stock_price_adj_close>39.97</stock_price_adj_close>
</NYSE_Daily_Prices>
<NYSE_Daily_Prices>
<stock_exchange>NYSE</stock_exchange>
<stock_symbol>ADI</stock_symbol>
<date>2000-01-04T00:00:00</date>
<stock_price_open>89.5</stock_price_open>
<stock_price_high>91.5</stock_price_high>
<stock_price_low>85.56</stock_price_low>
<stock_price_close>85.62</stock_price_close>
<stock_volume>2533200</stock_volume>
<stock_price_adj_close>37.95</stock_price_adj_close>
</NYSE_Daily_Prices>
<NYSE_Daily_Prices>
<stock_exchange>NYSE</stock_exchange>
<stock_symbol>ADI</stock_symbol>
<date>2000-01-05T00:00:00</date>
<stock_price_open>85.62</stock_price_open>
<stock_price_high>88.25</stock_price_high>
<stock_price_low>83.19</stock_price_low>
<stock_price_close>86.88</stock_price_close>
<stock_volume>3228000</stock_volume>
<stock_price_adj_close>38.51</stock_price_adj_close>
</NYSE_Daily_Prices>
</Prices>
</root>
我又创建了 1 个班级 Root
:
[XmlRoot("root")]
public class Root
[XmlArray("Prices")]
[XmlArrayItem("NYSE_Daily_Prices")]
public List<NYSE_Daily_Prices> Prices get; set; = new List<NYSE_Daily_Prices>();
在控制台应用程序中测试了这段代码,它工作正常:
class Program
static void Main(string[] args)
var deserializedObject = XmlHelper.FromXmlFile<Root>(Environment.CurrentDirectory + @"\file.xml");
希望对你有帮助!
【讨论】:
谢谢 Anna,您将根元素添加到 xml 文件是对的。我没有为调试文件添加位置。在我这样做之后,我执行了代码并接受了路径,但是由于重复的根元素,xml 文件有一个内部异常。现在一切正常:)以上是关于如何将 XML 反序列化为 C# 中的对象? [复制]的主要内容,如果未能解决你的问题,请参考以下文章
将 Web 服务 API 中的 XML 字符串反序列化为 C# 对象
将 xml 反序列化为 c# 对象时,XML 文档 (2, 2) 出现错误