[英]Deserializing XML File with multiple element attributes - attributes are not deserializing
[英]Deserializing XML File attributes
我正在嘗試反序列化以下 xml 文件:
<item>
<title>Title</title>
<link>https://blog.sitename.com/link</link> <comments>https://blog.sitename.com/link/#respond</comments>
<dc:creator><![CDATA[name]]></dc:creator>
<pubDate>Thu, 30 Apr 2020 18:59:06 +0000</pubDate>
<description><p>description...</p><p> continue</p></description>
<category><![CDATA[General News]]></category>
<media:content url="https://blog.gotproperty.co.za/wp-content/uploads/2020/04/image.jpg" medium="image" />
</item>
我的 class 如下
[XmlRoot("item")]
public class item
{
public string title { get; set; }
public string link { get; set; }
public string comments{ get; set; }
[XmlElement("media:content")]
public Image Image { get; set; }
public string description { get; set; }
public string shortDescription
{
get
{
var decodeHtml = HttpUtility.HtmlDecode(description);
var result = decodeHtml.Substring(decodeHtml.IndexOf('>') +1, decodeHtml.IndexOf("</") - decodeHtml.IndexOf('>') -1);
return result;
}
}
}
public class Image
{
[XmlAttribute("url")]
public string url { get; set; }
[XmlAttribute("medium")]
public string medium { get; set; }
}
除了使用圖像 class 的“media:content”元素之外,所有內容都在解析,其中 url 和 medium 定義為 XmlAttributes。
<media:content>
不是 xml 元素名稱; 那是<content>
,但是在命名空間中,無論您有別名xmlns:media
指的是什么; 所以如果你有xmlns:media="http://foo/bar"
,那么這是:
[XmlElement("content", Namespace = "http://foo/bar")]
public Image Image { get; set; }
明確地說:如果你有xmlns:media="http://foo/bar"
,那么: <media:content>
類似於<content xmlns="http://foo/bar">
,除了命名空間"http://foo/bar"
不被子元素繼承。
更新 Marc Gravell 的答案。
抱歉沒有意識到 Xml header 是必需的,所以我只發布了 Xml 文件的片段。
Xml header
<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
xmlns:media="http://search.yahoo.com/mrss/"
>
Class 更新
[XmlElement("content", Namespace = "http://search.yahoo.com/mrss/")]
public Image Image { get; set; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.