代码之家  ›  专栏  ›  技术社区  ›  TheBoubou codingbadger

使用yield返回IEnumerable<xelement>时将XML反序列化为C对象

  •  0
  • TheBoubou codingbadger  · 技术社区  · 6 年前

    当我试图对XML文件进行反序列化时出现此错误 XML文档(1,2)中有错误。

    我在韦恩周围搜索了几次,但都没有成功。

    //The XML
    <?xml version="1.0" encoding="utf-8"?>
    <books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <book>
        <bookid>9d6378e5-e01d-454d-bae5-52d9a6331f2e</bookid>
        <updatedate>2008-04-25</updatedate>
      </book>
    </books>
    
    public class MyBook
    {
        public string BookId { get; set; }
        public DateTime UpdateDate { get; set; }
    }
    
    //I read the file, working
    public IEnumerable<XElement> XElements()
    {
        using (XmlReader reader = XmlReader.Create(this._filePath))
        {
            reader.MoveToContent();
    
            while (reader.Read())
            {
                if (reader.Name == "book")
                {
                    XElement element = XElement.ReadFrom(reader) as XElement;
                    if (element != null)
                        yield return element;
                }
            }
        }
    }
    
    //When I try to Deserialize that's crash
    [TestMethod]
    public void ReadXmlTest()
    {
        ReadXmlFile readXmlFile = new ReadXmlFile(thepath);
        IEnumerable<XElement> xElements = readXmlFile.XElements();
    
        foreach (XElement e in xElements)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(MyBook));
            using (StringReader myStream = new StringReader(e.ToString()))
            {
                MyBook res = (MyBook)serializer.Deserialize(myStream);
            }
    
            //I gtried this solution too
            //XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyBook));
            //MyBook myBook = (MyBook)xmlSerializer.Deserialize(e.CreateReader());
        }
    } 
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Alexander Petrov    6 年前

    你的班级模型应该是这样的

    [XmlRoot("book")]
    public class MyBook
    {
        [XmlElement("bookid")]
        public string BookId { get; set; }
        [XmlElement("updatedate")]
        public DateTime UpdateDate { get; set; }
    }
    

    因为XML元素的名称与类和属性的名称不匹配。