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

时间:2018-06-18 15:18:06

标签: c# .net xml deserialization

当我尝试解压缩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 个答案:

答案 0 :(得分:2)

您的班级模型应如下所示

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

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