将XML反序列化为对象

时间:2020-10-28 11:45:36

标签: c# xml deserialization

因此,我一直在尝试将此xml文件反序列化为某些对象,它虽然很简单,但是一直向对象返回null,我需要的数据存储在元素的属性内。

这是XML。

 <exchangerates xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" type="Valutakurser" author="Danmarks Nationalbank" refcur="DKK" refamt="1">
<dailyrates id="2020-10-20">
    <currency code="AUD" desc="Australske dollar" rate="442,98"/>
    <currency code="BGN" desc="Bulgarske lev" rate="380,53"/>
</dailyrates>

这是反序列化代码。

public static T DeserializeElement<T>(string filename)
    {
        try
        {
            T result;
            XmlSerializer serializer = new XmlSerializer(typeof(T), new 
            XmlRootAttribute("exchangerates"));
            
            using (TextReader tr = new StringReader(filename))
            {
                result = (T)serializer.Deserialize(tr);
            }

            return result;
        }
        catch { throw; }
    } 

这些是对象

[XmlRoot(Namespace = "http://www.w3.org/2001/XMLSchema-instance",
ElementName = "exchangerates",
DataType = "Valutakurser")]
[Serializable]
public class Valutakurser
{
    
    [XmlArray("dailyrates")]
    public DateTime Id { get; set; }
    public Currency Currency { get; set; }
}

[Serializable]
public class Currency
{
    public string Code { get; set; }
    public string Desc { get; set; }
    public double Rate { get; set; }

    public Currency() { }
}

目前,我一直收到此错误,并且所有内容均返回null:

InvalidOperationException:对于非数组类型,可以使用以下属性:XmlAttribute,XmlText,XmlElement或XmlAnyElement

1 个答案:

答案 0 :(得分:0)

尝试以下操作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlReader reader = XmlReader.Create(FILENAME);
            XmlSerializer serializer = new XmlSerializer(typeof(Valutakurser));
            Valutakurser valutakurser = (Valutakurser)serializer.Deserialize(reader);

        }
    }
    [XmlRoot(ElementName = "exchangerates")]
    public class Valutakurser
    {
        [XmlAttribute]
        public DateTime id { get; set; }
        [XmlElement("dailyrates")]
        public DailyRates DalyRates { get; set; }
    }
    public class DailyRates
    {
        [XmlElement("currency")]
        public List<Currency> Currency { get; set; }
    }

    public class Currency
    {
        [XmlAttribute]
        public string code { get; set; }
        [XmlAttribute]
        public string desc { get; set; }
        [XmlAttribute]
        public double rate { get; set; }

        public Currency() { }
    }

}