XML反序列化将无法工作:返回空记录

时间:2018-06-25 10:27:20

标签: c# xml

下面是我的标本和代码。我只是想不出问题出在哪里,我被困了好几天。...请求救!

我的XML和下面的实体

<?xml version="1.0" encoding="windows-1251"?>
<root>
<record>
    <ID>1</ID>
    <NAME>YOUSUF YSAI</NAME>
</record>
<record>
    <ID>2</ID>
    <NAME>MOHAMMED YSAI </NAME>
</record>
</root>


  public class Root
  {
    public List<Record> records {get; set;}
  }

  public class Record
  {
    public string ID {get; set;}
     public string Name {get; set;}
  }

我的XML反序列化扩展方法:

    public static T Deserialize<T>(this string xml)
    {
        XmlRootAttribute xRoot = new XmlRootAttribute();
        xRoot.ElementName = "root";
        //  xRoot.Namespace = "";
        xRoot.IsNullable = true;

        XmlSerializer serializer = new XmlSerializer(typeof(T),xRoot);
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.DtdProcessing = DtdProcessing.Ignore;
        settings.ConformanceLevel = ConformanceLevel.Document;


        using (StringReader textReader = new StringReader(xml))
        {
            using (XmlReader xmlReader = XmlReader.Create(textReader, settings))
            {
                return (T)serializer.Deserialize(xmlReader);
            }
        }
    }

这就是我叫反序列化的方式

    string xml = File.ReadAllText(file.Directory.FullName + "\\" + filename);
    Root root = xml.Deserialize<Root>();

没有返回异常,但更令人讨厌的是,也没有返回记录...

1 个答案:

答案 0 :(得分:0)

为此更新您的课程:-

[XmlRoot(ElementName = "root")]
public class Root
{
    [XmlElement(ElementName = "record")]
    public List<Record> records { get; set; }
}
public class Record
{
    [XmlElement(ElementName = "ID")]
    public string ID { get; set; }
    [XmlElement(ElementName = "NAME")]
    public string Name { get; set; }
}

这是整个工作示例:-

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string data = File.ReadAllText("D://check.xml");//your xml code is in file name check.xml
            var streamdata = new MemoryStream(Encoding.UTF8.GetBytes(data ?? ""));
            Stream st = streamdata;
            Root ro = new Root();
            XmlSerializer xml = new XmlSerializer(typeof(Root));
            ro=(Root)xml.Deserialize(st);

        }
    }
    [XmlRoot(ElementName = "root")]
    public class Root
    {
        [XmlElement(ElementName = "record")]
        public List<Record> records { get; set; }
    }

    public class Record
    {
        [XmlElement(ElementName = "ID")]
        public string ID { get; set; }
        [XmlElement(ElementName = "NAME")]
        public string Name { get; set; }
    }
}