多命名空间的XML反序列化

8
我将尝试将以下XML反序列化为对象。 XML中有多个命名空间。 我尝试将XML反序列化为对象。 该对象(数据)引用了LastChannel对象。 但是当我请求data.channel时应该返回LastChannel,但我得到了一个nullpointer。
XML:
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
         xmlns="http://purl.org/rss/1.0/"
         xmlns:dc="http://purl.org/dc/elements/1.1/"
         xmlns:mp="http://www.tagesschau.de/rss/1.0/modules/metaplus/"
         xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
         xmlns:content="http://purl.org/rss/1.0/modules/content/">

<channel>
<title>title</title>
<description>Default description</description>
<dc:date>2013-04-15 13:27:06</dc:date>
<sy:updateBase>2013-04-15 13:27:06</sy:updateBase>
<sy:updatePeriod>hourly</sy:updatePeriod>
<sy:updateFrequency>12</sy:updateFrequency>
</channel>
</rdf:RDF>

对象看起来像这样:
[XmlRoot("RDF", Namespace = "http://www.w3.org/1999/02/22-rdf-syntax-ns#")]
public class LastRss
{
   [XmlElement("channel")]
   public LastChannel channel { get; set; }
} 

并且

public class LastChannel
{
    [XmlElement("title")]
    public string title { get; set; }
    [XmlElement("description")]
    public string description { get; set; }
    [XmlElement("date", Namespace = "http://purl.org/dc/elements/1.1/")]
    public DateTime date { get; set; }
    [XmlElement("updateBase", Namespace = "http://purl.org/rss/1.0/modules/syndication/")]
    public DateTime updateBase { get; set; }
    [XmlElement("updatePeriod", Namespace = "http://purl.org/rss/1.0/modules/syndication/")]
    public string updatePeriod { get; set; }
    [XmlElement("updateFrequency", Namespace = "http://purl.org/rss/1.0/modules/syndication/")]
    public int updateFrequency { get; set; }
}

有人能看出为什么data.channel是null吗?

序列化器:

LastRss data = new LastRss();
XmlSerializer serializer = new XmlSerializer(typeof(LastRss));
System.IO.TextReader reader = new System.IO.StringReader(xml);
try
{
    object o = serializer.Deserialize(reader);
    data = (LastRss)o;
}
1个回答

5

您的频道位于默认的xmlns中,即http://purl.org/rss/1.0/

  [XmlElement("channel", Namespace = "http://purl.org/rss/1.0/")]
  public LastChannel channel { get; set; }

您还需要纠正日期格式,例如2013-04-15T13:27:06


1
太好了!非常感谢! - flo1411

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接