如何将XML反序列化为C#中的对象?

如何将XML反序列化为C#中的对象?,c#,xml,C#,Xml,我需要读取XML并将其反序列化为C#中的对象。我使用下面给出的ToXmlFile(objectobj,stringfilepath)函数的序列化部分创建了该文件。我在test.XML文件中创建了以下XML: <NYSE_Daily_Prices> <stock_exchange>NYSE</stock_exchange> <stock_symbol>ADI</stock_symbol> <date>2

我需要读取XML并将其反序列化为C#中的对象。我使用下面给出的ToXmlFile(objectobj,stringfilepath)函数的序列化部分创建了该文件。我在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 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();
        }
    }
}

任何帮助都将不胜感激:)

戴维德。我觉得你的代码很好。我在当地试过

您确定提供了文件的正确路径吗

我改变了一点xml,因为我假设它应该有一个根元素。现在.xml文件如下所示:


纽约证券交易所
阿迪
2000-01-03T00:00:00
93.5
93.87
88
90.19
3655600
39.97
纽约证券交易所
阿迪
2000-01-04T00:00:00
89.5
91.5
85.56
85.62
2533200
37.95
纽约证券交易所
阿迪
2000-01-05T00:00:00
85.62
88.25
83.19
86.88
3228000
38.51
我又创建了一个类
Root

[XmlRoot(“根”)]
公共类根
{
[XmlArray(“价格”)]
[XmlArrayItem(“纽约证券交易所每日价格”)]
公开标价{get;set;}=new List();
}
在控制台应用程序中测试此代码,效果良好:

    class Program
    {
        static void Main(string[] args)
        {
            var deserializedObject = XmlHelper.FromXmlFile<Root>(Environment.CurrentDirectory + @"\file.xml");
        }
    }
类程序
{
静态void Main(字符串[]参数)
{
var deserializedObject=XmlHelper.FromXmlFile(Environment.CurrentDirectory+@“\file.xml”);
}
}


我希望有帮助

当抛出一个新异常(顺便说一下,它不应该是基本异常类)时,只需将实际异常作为内部异常。现在,内部异常是怎么说的呢?
throw
的参数包括
e.InnerException.Message
,但是您没有显示该throw的输出,也没有编写代码来显示
e.Message
。谢谢Anna,您将根元素添加到xml文件的想法是正确的。我没有为调试文件添加位置。在我这样做之后,我执行了代码,路径被接受,但是由于重复的根元素,xml文件有一个内部异常。现在一切正常:)
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);
            }
    class Program
    {
        static void Main(string[] args)
        {
            var deserializedObject = XmlHelper.FromXmlFile<Root>(Environment.CurrentDirectory + @"\file.xml");
        }
    }