2 // Rss20FeedFormatter.cs
5 // Atsushi Enomoto <atsushi@ximian.com>
7 // Copyright (C) 2007 Novell, Inc (http://www.novell.com)
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 using System.Collections.Generic;
30 using System.Collections.ObjectModel;
31 using System.Globalization;
33 using System.Runtime.Serialization;
36 using System.Xml.Schema;
37 using System.Xml.Serialization;
39 namespace System.ServiceModel.Syndication
41 [XmlRoot ("rss", Namespace = "")]
42 public class Rss20FeedFormatter : SyndicationFeedFormatter, IXmlSerializable
44 const string AtomNamespace ="http://www.w3.org/2005/Atom";
46 bool ext_atom_serialization, preserve_att_ext = true, preserve_elem_ext = true;
49 public Rss20FeedFormatter ()
51 ext_atom_serialization = true;
54 public Rss20FeedFormatter (SyndicationFeed feedToWrite)
55 : this (feedToWrite, true)
59 public Rss20FeedFormatter (SyndicationFeed feedToWrite, bool serializeExtensionsAsAtom)
62 ext_atom_serialization = serializeExtensionsAsAtom;
65 public Rss20FeedFormatter (Type feedTypeToCreate)
67 if (feedTypeToCreate == null)
68 throw new ArgumentNullException ("feedTypeToCreate");
69 feed_type = feedTypeToCreate;
72 public bool SerializeExtensionsAsAtom {
73 get { return ext_atom_serialization; }
74 set { ext_atom_serialization = value; }
77 protected Type FeedType {
78 get { return feed_type; }
81 public bool PreserveAttributeExtensions {
82 get { return preserve_att_ext; }
83 set { preserve_att_ext = value; }
86 public bool PreserveElementExtensions {
87 get { return preserve_elem_ext; }
88 set { preserve_elem_ext = value; }
91 public override string Version {
92 get { return "Rss20"; }
95 protected override SyndicationFeed CreateFeedInstance ()
97 return new SyndicationFeed ();
100 // hmm, why is it overriden? probably failed API cleanup.
101 protected internal override void SetFeed (SyndicationFeed feed)
106 public override bool CanRead (XmlReader reader)
109 throw new ArgumentNullException ("reader");
110 reader.MoveToContent ();
111 return reader.IsStartElement ("rss", String.Empty);
114 public override void ReadFrom (XmlReader reader)
116 if (!CanRead (reader))
117 throw new XmlException (String.Format ("Element '{0}' in namespace '{1}' is not accepted by this syndication formatter", reader.LocalName, reader.NamespaceURI));
118 ReadXml (reader, true);
121 protected virtual SyndicationItem ReadItem (XmlReader reader, SyndicationFeed feed)
123 Rss20ItemFormatter formatter = new Rss20ItemFormatter();
124 formatter.ReadFrom (reader);
125 return formatter.Item;
128 protected virtual IEnumerable<SyndicationItem> ReadItems (XmlReader reader, SyndicationFeed feed, out bool areAllItemsRead)
130 Collection<SyndicationItem> c = new Collection<SyndicationItem> ();
131 for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ())
132 if (reader.LocalName == "item" && reader.NamespaceURI == String.Empty)
133 c.Add (ReadItem (reader, feed));
134 areAllItemsRead = (reader.NodeType == XmlNodeType.EndElement);
138 protected virtual void WriteItem (XmlWriter writer, SyndicationItem item, Uri feedBaseUri)
140 item.SaveAsRss20 (writer);
143 protected virtual void WriteItems (XmlWriter writer, IEnumerable<SyndicationItem> items, Uri feedBaseUri)
146 throw new ArgumentNullException ("items");
147 foreach (SyndicationItem item in items)
148 WriteItem (writer, item, feedBaseUri);
151 public override void WriteTo (XmlWriter writer)
153 WriteXml (writer, true);
156 void IXmlSerializable.ReadXml (XmlReader reader)
158 ReadXml (reader, false);
161 void IXmlSerializable.WriteXml (XmlWriter writer)
163 WriteXml (writer, false);
166 XmlSchema IXmlSerializable.GetSchema ()
173 void ReadXml (XmlReader reader, bool fromSerializable)
176 throw new ArgumentNullException ("reader");
177 SetFeed (CreateFeedInstance ());
179 reader.MoveToContent ();
181 string ver = reader.GetAttribute ("version");
183 throw new NotSupportedException (String.Format ("RSS Version '{0}' is not supported", ver));
185 if (PreserveAttributeExtensions && reader.MoveToFirstAttribute ()) {
187 if (reader.NamespaceURI == "http://www.w3.org/2000/xmlns/")
189 if (reader.NamespaceURI == String.Empty && reader.LocalName == "version")
191 if (!TryParseAttribute (reader.LocalName, reader.NamespaceURI, reader.Value, Feed, Version))
192 Feed.AttributeExtensions.Add (new XmlQualifiedName (reader.LocalName, reader.NamespaceURI), reader.Value);
193 } while (reader.MoveToNextAttribute ());
196 reader.ReadStartElement (); // <rss> => <channel>
197 reader.MoveToContent ();
198 reader.ReadStartElement ("channel", String.Empty); // <channel> => *
200 Collection<SyndicationItem> items = null;
202 for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
203 if (reader.NodeType != XmlNodeType.Element)
204 throw new XmlException ("Only element node is expected under 'channel' element");
205 if (reader.NamespaceURI == String.Empty)
206 switch (reader.LocalName) {
208 Feed.Title = ReadTextSyndicationContent (reader);
211 SyndicationLink l = Feed.CreateLink ();
212 ReadLink (reader, l);
216 Feed.Description = ReadTextSyndicationContent (reader);
219 Feed.Language = reader.ReadElementContentAsString ();
222 Feed.Copyright = ReadTextSyndicationContent (reader);
224 case "managingEditor":
225 SyndicationPerson p = Feed.CreatePerson ();
226 ReadPerson (reader, p);
227 Feed.Authors.Add (p);
230 // FIXME: somehow DateTimeOffset causes the runtime crash.
231 reader.ReadElementContentAsString ();
232 // Feed.PublishDate = FromRFC822DateString (reader.ReadElementContentAsString ());
234 case "lastBuildDate":
235 // FIXME: somehow DateTimeOffset causes the runtime crash.
236 reader.ReadElementContentAsString ();
237 // Feed.LastUpdatedTime = FromRFC822DateString (reader.ReadElementContentAsString ());
240 SyndicationCategory c = Feed.CreateCategory ();
241 ReadCategory (reader, c);
242 Feed.Categories.Add (c);
245 Feed.Generator = reader.ReadElementContentAsString ();
247 // "webMaster" "docs" "cloud" "ttl" "image" "rating" "textInput" "skipHours" "skipDays" are not handled.
250 items = new Collection<SyndicationItem> ();
253 items.Add (ReadItem (reader, Feed));
256 if (!TryParseElement (reader, Feed, Version)) {
257 if (PreserveElementExtensions)
258 // FIXME: what to specify for maxExtensionSize
259 LoadElementExtensions (reader, Feed, int.MaxValue);
265 reader.ReadEndElement (); // </channel>
266 reader.ReadEndElement (); // </rss>
269 TextSyndicationContent ReadTextSyndicationContent (XmlReader reader)
271 TextSyndicationContentKind kind = TextSyndicationContentKind.Plaintext;
272 switch (reader.GetAttribute ("type")) {
274 kind = TextSyndicationContentKind.Html;
277 kind = TextSyndicationContentKind.XHtml;
280 string text = reader.ReadElementContentAsString ();
281 TextSyndicationContent t = new TextSyndicationContent (text, kind);
285 void ReadCategory (XmlReader reader, SyndicationCategory category)
287 if (reader.MoveToFirstAttribute ()) {
289 if (reader.NamespaceURI == "http://www.w3.org/2000/xmlns/")
291 if (reader.NamespaceURI == String.Empty) {
292 switch (reader.LocalName) {
294 category.Scheme = reader.Value;
298 if (PreserveAttributeExtensions)
299 if (!TryParseAttribute (reader.LocalName, reader.NamespaceURI, reader.Value, category, Version))
300 category.AttributeExtensions.Add (new XmlQualifiedName (reader.LocalName, reader.NamespaceURI), reader.Value);
301 } while (reader.MoveToNextAttribute ());
302 reader.MoveToElement ();
305 if (!reader.IsEmptyElement) {
307 for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
308 if (reader.IsTextNode ())
309 category.Name += reader.Value;
310 else if (!TryParseElement (reader, category, Version)) {
311 if (PreserveElementExtensions)
312 // FIXME: what should be used for maxExtenswionSize
313 LoadElementExtensions (reader, category, int.MaxValue);
320 reader.Read (); // </category> or <category ... />
323 void ReadLink (XmlReader reader, SyndicationLink link)
325 if (PreserveAttributeExtensions && reader.MoveToFirstAttribute ()) {
327 if (reader.NamespaceURI == "http://www.w3.org/2000/xmlns/")
329 if (!TryParseAttribute (reader.LocalName, reader.NamespaceURI, reader.Value, link, Version))
330 link.AttributeExtensions.Add (new XmlQualifiedName (reader.LocalName, reader.NamespaceURI), reader.Value);
331 } while (reader.MoveToNextAttribute ());
332 reader.MoveToElement ();
335 if (!reader.IsEmptyElement) {
338 for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
339 if (reader.IsTextNode ())
341 else if (!TryParseElement (reader, link, Version)) {
342 if (PreserveElementExtensions)
343 // FIXME: what should be used for maxExtenswionSize
344 LoadElementExtensions (reader, link, int.MaxValue);
350 link.Uri = CreateUri (url);
352 reader.Read (); // </link> or <link ... />
355 void ReadPerson (XmlReader reader, SyndicationPerson person)
357 if (PreserveAttributeExtensions && reader.MoveToFirstAttribute ()) {
359 if (reader.NamespaceURI == "http://www.w3.org/2000/xmlns/")
361 if (!TryParseAttribute (reader.LocalName, reader.NamespaceURI, reader.Value, person, Version))
362 person.AttributeExtensions.Add (new XmlQualifiedName (reader.LocalName, reader.NamespaceURI), reader.Value);
363 } while (reader.MoveToNextAttribute ());
364 reader.MoveToElement ();
367 if (!reader.IsEmptyElement) {
369 for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
370 if (reader.IsTextNode ())
371 person.Email += reader.Value;
372 else if (!TryParseElement (reader, person, Version)) {
373 if (PreserveElementExtensions)
374 // FIXME: what should be used for maxExtenswionSize
375 LoadElementExtensions (reader, person, int.MaxValue);
382 reader.Read (); // end element or empty element
385 Uri CreateUri (string uri)
387 return new Uri (uri, UriKind.RelativeOrAbsolute);
392 void WriteXml (XmlWriter writer, bool writeRoot)
395 throw new ArgumentNullException ("writer");
397 throw new InvalidOperationException ("Syndication feed must be set before writing");
400 writer.WriteStartElement ("rss");
402 if (SerializeExtensionsAsAtom)
403 writer.WriteAttributeString ("xmlns", "a10", "http://www.w3.org/2000/xmlns/", AtomNamespace);
404 writer.WriteAttributeString ("version", "2.0");
406 writer.WriteStartElement ("channel");
408 if (Feed.BaseUri != null)
409 writer.WriteAttributeString ("xml:base", Feed.BaseUri.ToString ());
411 writer.WriteElementString ("title", String.Empty, Feed.Title != null ? Feed.Title.Text : String.Empty);
413 writer.WriteElementString ("description", String.Empty, Feed.Description != null ? Feed.Description.Text : String.Empty);
415 if (Feed.Copyright != null)
416 writer.WriteElementString ("copyright", String.Empty, Feed.Copyright.Text);
418 if (!Feed.LastUpdatedTime.Equals (default (DateTimeOffset))) {
419 writer.WriteStartElement ("lastBuildDate");
420 writer.WriteString (ToRFC822DateString (Feed.LastUpdatedTime));
421 writer.WriteEndElement ();
424 if (Feed.Generator != null)
425 writer.WriteElementString ("generator", String.Empty, Feed.Generator);
426 if (Feed.ImageUrl != null) {
427 writer.WriteStartElement ("image");
428 writer.WriteElementString ("url", String.Empty, Feed.ImageUrl.ToString ());
429 // FIXME: are they really empty?
430 writer.WriteElementString ("title", String.Empty, String.Empty);
431 writer.WriteElementString ("link", String.Empty, String.Empty);
432 writer.WriteEndElement ();
434 if (Feed.Language != null)
435 writer.WriteElementString ("language", String.Empty, Feed.Language);
437 foreach (SyndicationPerson author in Feed.Authors)
438 if (author != null) {
439 writer.WriteStartElement ("managingEditor");
440 WriteAttributeExtensions (writer, author, Version);
441 writer.WriteString (author.Email);
442 WriteElementExtensions (writer, author, Version);
443 writer.WriteEndElement ();
445 foreach (SyndicationCategory category in Feed.Categories)
446 if (category != null) {
447 writer.WriteStartElement ("category");
448 if (category.Scheme != null)
449 writer.WriteAttributeString ("domain", category.Scheme);
450 WriteAttributeExtensions (writer, category, Version);
451 writer.WriteString (category.Name);
452 WriteElementExtensions (writer, category, Version);
453 writer.WriteEndElement ();
456 foreach (SyndicationLink link in Feed.Links)
458 writer.WriteStartElement ("link");
459 WriteAttributeExtensions (writer, link, Version);
460 writer.WriteString (link.Uri != null ? link.Uri.ToString () : String.Empty);
461 WriteElementExtensions (writer, link, Version);
462 writer.WriteEndElement ();
465 WriteItems (writer, Feed.Items, Feed.BaseUri);
467 if (SerializeExtensionsAsAtom) {
469 if (Feed.Id != null) {
470 writer.WriteStartElement ("a10", "id", AtomNamespace);
471 writer.WriteString (Feed.Id);
472 writer.WriteEndElement ();
475 foreach (SyndicationPerson contributor in Feed.Contributors) {
476 if (contributor != null) {
477 writer.WriteStartElement ("a10", "contributor", AtomNamespace);
478 WriteAttributeExtensions (writer, contributor, Version);
479 writer.WriteElementString ("a10", "name", AtomNamespace, contributor.Name);
480 writer.WriteElementString ("a10", "uri", AtomNamespace, contributor.Uri);
481 writer.WriteElementString ("a10", "email", AtomNamespace, contributor.Email);
482 WriteElementExtensions (writer, contributor, Version);
483 writer.WriteEndElement ();
488 writer.WriteEndElement (); // </channel>
491 writer.WriteEndElement (); // </rss>
494 // FIXME: DateTimeOffset.ToString() needs another overload.
495 // When it is implemented, just remove ".DateTime" parts below.
496 string ToRFC822DateString (DateTimeOffset date)
498 switch (date.DateTime.Kind) {
499 case DateTimeKind.Utc:
500 return date.DateTime.ToString ("ddd, dd MMM yyyy HH:mm:ss 'Z'", DateTimeFormatInfo.InvariantInfo);
501 case DateTimeKind.Local:
502 StringBuilder sb = new StringBuilder (date.DateTime.ToString ("ddd, dd MMM yyyy HH:mm:ss zzz", DateTimeFormatInfo.InvariantInfo));
503 sb.Remove (sb.Length - 3, 1);
504 return sb.ToString (); // remove ':' from +hh:mm
506 return date.DateTime.ToString ("ddd, dd MMM yyyy HH:mm:ss", DateTimeFormatInfo.InvariantInfo);