繁体   English   中英

XML 反序列化为对象

[英]XML deserialization to object

所以我一直试图将这个 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() { }
}

目前我不断收到此错误,一切都返回空值:

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

尝试以下:

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() { }
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM