将xml反序列化为对象返回null

时间:2018-05-21 09:10:02

标签: c# xml object

它正确计算了对象的数量但返回null或者零。我有很多类来填充xml内容。我需要一种有效的方法将xml导入我的C#app。我的xml文件是否已损坏?

Xml文件:

<Entitati>
  <Entitate>
    <nume>asd</nume>
    <actiuni>25</actiuni>
    <valoare>2.05</valoare>
  </Entitate>
  <Entitate>
    <nume>fgh</nume>
    <actiuni>50</actiuni>
    <valoare>3.14</valoare>
  </Entitate>
  <Entitate>
    <nume>fanel</nume>
    <actiuni>35</actiuni>
    <valoare>5.15</valoare>
  </Entitate>
</Entitati>

类:

[XmlRoot("Entitati")]
public class Entitati
{
    [XmlElement("Entitate")]
    public List<Entitate> entitati { get; set; }
}

[XmlRoot("Entitate")]
public class Entitate
{
     [XmlElement("nume")]
     protected string nume { get; set; }
     [XmlElement("actiuni")]
     protected int actiuniDisponibile { get; set; }
     [XmlElement("valoare")]
     protected double valoareActiune { get; set; }
}

主要

XmlSerializer serializer = new XmlSerializer(typeof(Entitati));
using (FileStream fileStream = new 
FileStream("C:\\Users\\batrinut\\Desktop\\Entitati.xml", FileMode.Open))
{
      Entitati result = (Entitati)serializer.Deserialize(fileStream);
}

1 个答案:

答案 0 :(得分:0)

Entitate类中的属性不应为protected

然后更改为public应该可以解决问题。

namespace SOTest
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Entitati));
            using (FileStream fileStream = new FileStream("data.xml", FileMode.Open))
            {
                Entitati result = (Entitati)serializer.Deserialize(fileStream);

                Console.ReadKey();
            }
        }
    }

    [XmlRoot("Entitati")]
    public class Entitati
    {
        [XmlElement("Entitate")]
        public List<Entitate> entitati { get; set; }
    }

    [XmlRoot("Entitate")]
    public class Entitate
    {
        [XmlElement("nume")]
        public string nume { get; set; }

        [XmlElement("actiuni")]
        public int actiuniDisponibile { get; set; }

        [XmlElement("valoare")]
        public double valoareActiune { get; set; }
    }
}