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

11 浏览
0 Comments

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

这个问题已经有了答案:

如何反序列化XML文档

我需要在C#中读取XML并将其反序列化为对象。我使用下面给出的ToXmlFile(Object obj,string filePath)函数的序列化部分创建文件。我在文件test.xml中创建了以下XML:

    NYSE
    ADI
    2000-01-03T00:00:00
    93.5
    93.87
    88
    90.19
    3655600
    39.97
  
  
    NYSE
    ADI
    2000-01-04T00:00:00
    89.5
    91.5
    85.56
    85.62
    2533200
    37.95
  
  
    NYSE
    ADI
    2000-01-05T00:00:00
    85.62
    88.25
    83.19
    86.88
    3228000
    38.51
  

这是我的对象:

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; }
    ///
    /// Serializes an object to an XML string, using the specified namespaces.
    ///

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(); } ///

    /// Serializes an object to an XML string.
    ///

public static string ToXml(object obj) { var ns = new XmlSerializerNamespaces(); ns.Add("", ""); return ToXml(obj, ns); } ///

    /// Deserializes an object from an XML string.
    ///

public static T FromXml(string xml) { XmlSerializer xs = new XmlSerializer(typeof(T)); using (StringReader sr = new StringReader(xml)) { return (T)xs.Deserialize(sr); } } ///

    /// Deserializes an object from an XML string, using the specified type name.
    ///

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); } } ///

    /// Serializes an object to an XML file.
    ///

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); } } ///

    /// Deserializes an object from an XML file.
    ///

public static T FromXmlFile(string filePath) { StreamReader sr = new StreamReader(filePath); try { var result = FromXml(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(filePath);

我不断遇到抛出的异常:

catch (Exception e)
                {
                    throw new Exception("There was an error attempting to read the file " + filePath + "\n\n" + e.InnerException.Message);
            }

任何帮助将不胜感激 🙂

admin 更改状态以发布 2023年5月21日
0
0 Comments

Davide。你的代码看起来很好。我在本地尝试了一下。

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

我稍微修改了一下xml文件,因为我假设它应该有一个根元素。现在.xml文件看起来像这样:


  
    
      NYSE
      ADI
      2000-01-03T00:00:00
      93.5
      93.87
      88
      90.19
      3655600
      39.97
    
    
      NYSE
      ADI
      2000-01-04T00:00:00
      89.5
      91.5
      85.56
      85.62
      2533200
      37.95
    
    
      NYSE
      ADI
      2000-01-05T00:00:00
      85.62
      88.25
      83.19
      86.88
      3228000
      38.51
    
  

我创建了另外一个类Root

    [XmlRoot("root")]
    public class Root
    {
        [XmlArray("Prices")]
        [XmlArrayItem("NYSE_Daily_Prices")]
        public List Prices { get; set; } = new List();
    }

在控制台应用程序中测试了这段代码,它运行得很好:

    class Program
    {
        static void Main(string[] args)
        {
            var deserializedObject = XmlHelper.FromXmlFile(Environment.CurrentDirectory + @"\file.xml");
        }
    }

enter image description here

我希望它能够帮助你!

0