InvalidOperationException 反序列化 Atom XML

InvalidOperationException deserializing Atom XML

我正在使用此 C# 代码读取 XML RSS 提要并根据模型对其进行反序列化:

List<RssFeedModel> rssFeedItems = new List<RssFeedModel>();
var url = @"http://mimijumi-dev.myshopify.com/blogs/news.atom";
string result;
using (var httpClient = new HttpClient())
{
    var request = new HttpRequestMessage(HttpMethod.Get, url);
    var response = await httpClient.SendAsync(request);
    result = response.Content.ReadAsStringAsync().Result;
}
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(result.ToString());
XmlNodeReader xreader = new XmlNodeReader(xdoc);
XmlSerializer deserializer = new XmlSerializer(typeof(List<RssFeedModel>));
rssFeedItems = (List<RssFeedModel>)deserializer.Deserialize(xreader);

型号代码如下:

[XmlRoot("feed", Namespace = "http://www.w3.org/2005/Atom")]
public class RssFeedModel
{
    [XmlElement("title")]
    public string Title { get; set; }

    [XmlElement("content")]
    public string Content { get; set; }

    [XmlElement("link")]
    public string Link { get; set; }

    [XmlElement("id")]
    public int Id { get; set; }

    [XmlElement("published")]
    public DateTime PublishDate { get; set; }

}

这将引发以下异常:

InvalidOperationException: <feed xmlns='http://www.w3.org/2005/Atom'> was not expected.
Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderList1.Read3_ArrayOfRssFeedModel()

对于这一行:

rssFeedItems = (List<RssFeedModel>)deserializer.Deserialize(xreader);

我按照这个 Whosebug post 中的说明尝试修复它: 但它仍在爆炸。

更新:这是XML它试图反序列化:

<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom" xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:s="http://jadedpixel.com/-/spec/shopify">
  <id>http://example.com/blogs/news.atom</id>
  <link rel="alternate" type="text/html" href="http://example.com/blogs/news"/>
  <link rel="self" type="application/atom+xml" href="http://example.com/blogs/news.atom"/>
  <title>News</title>
  <updated>2015-05-14T08:48:00-04:00</updated>
  <author>
    <name>Author</name>
  </author>
  <entry>
    <id>http://example.com/blogs/news/28298241-sixth-post</id>
    <published>2015-05-14T08:48:00-04:00</published>
    <updated>2015-05-14T08:48:49-04:00</updated>
    <link rel="alternate" type="text/html" href="http://example.com/blogs/news./28298241-sixth-post"/>
    <title>Sixth Post</title>
    <author>
      <name>Author</name>
    </author>
    <content type="html">
      <![CDATA[Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus consequat imperdiet. Vestibulum sapien. Proin quam. <br><br>Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. Sed lectus. Integer euismod lacus luctus magna. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi lacinia molestie dui. Praesent blandit dolor. Sed non quam. In vel mi sit amet augue congue elementum. Morbi in ipsum sit amet pede facilisis laoreet. Donec lacus nunc, viverra nec, blandit vel, egestas et, augue. Vestibulum tincidunt malesuada tellus. Ut ultrices ultrices enim.]]>
    </content>
  </entry>
  <entry>
    <id>http://example.com/blogs/news/28297985-fifth-post</id>
    <published>2015-05-14T08:48:00-04:00</published>
    <updated>2015-05-14T08:48:16-04:00</updated>
    <link rel="alternate" type="text/html" href="http://example.com/blogs/news/28297985-fifth-post"/>
    <title>Fifth Post</title>
    <author>
      <name>Author</name>
    </author>
    <content type="html">
      <![CDATA[Curabitur sit amet mauris. Morbi in dui quis est pulvinar ullamcorper. Nulla facilisi. Integer lacinia sollicitudin massa. Cras metus. Sed aliquet risus a tortor. Integer id quam. Morbi mi. Quisque nisl felis, venenatis tristique, dignissim in, ultrices sit amet, augue. Proin sodales libero eget ante. Nulla quam. Aenean laoreet. Vestibulum nisi lectus, commodo ac, facilisis ac, ultricies eu, pede. <br><br>Ut orci risus, accumsan porttitor, cursus quis, aliquet eget, justo. Sed pretium blandit orci. Ut eu diam at pede suscipit sodales. Aenean lectus elit, fermentum non, convallis id, sagittis at, neque. Nullam mauris orci, aliquet et, iaculis et, viverra vitae, ligula. Nulla ut felis in purus aliquam imperdiet. Maecenas aliquet mollis lectus. Vivamus consectetuer risus et tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet.]]>
    </content>
  </entry>
  <entry>
    <id>http://example.com/blogs/news/28297665-fourth-post</id>
    <published>2015-05-14T08:47:00-04:00</published>
    <updated>2015-05-14T08:47:43-04:00</updated>
    <link rel="alternate" type="text/html" href="http://example.com/blogs/news/28297665-fourth-post"/>
    <title>Fourth Post</title>
    <author>
      <name>Author</name>
    </author>
    <content type="html">
      <![CDATA[Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. <br><br>Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis turpis. Nulla facilisi. Ut fringilla.]]>
    </content>
  </entry>
 </feed>

试试这个。你有 link 作为一个字符串,它需要是一个单独的 class。还添加了 List<> 对象和属性,因此您可以查看如何正确反序列化 XML.

的示例

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

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlSerializer xs = new XmlSerializer(typeof(RssFeedModel));
            XmlTextReader reader = new XmlTextReader(FILENAME);
            RssFeedModel rssFeedModel = (RssFeedModel)xs.Deserialize(reader);

        }
    }
}
[XmlRoot("feed", Namespace = "http://www.w3.org/2005/Atom")]
public class RssFeedModel
{
    [XmlElement("title")]
    public string Title { get; set; }

    [XmlElement("link")]
    public List<Link> link { get; set; }

    [XmlElement("entry")]
    public List<Entry> entry { get; set; }
}
[XmlRoot("link")]
public class Link
{
    [XmlAttribute("rel")]
    public string rel { get; set; }
    [XmlAttribute("type")]
    public string type { get; set; }
}
[XmlRoot("entry")]
public class Entry
{
    [XmlElement("id")]
    public string Id { get; set; }

    [XmlElement("published")]
    public DateTime PublishDate { get; set; }

    [XmlElement("content")]
    public Content content { get; set; }
}
[XmlRoot("content")]
public class Content
{
    [XmlAttribute("type")]
    public string type { get; set; }
    [XmlText]
    public string text { get; set; }
}
​