Atom10ItemFormatter.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. //
  2. // Atom10ItemFormatter.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2007 Novell, Inc (http://www.novell.com)
  8. //
  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:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  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.
  27. //
  28. //
  29. // WARNING:
  30. // This class is not for outputting ATOM 1.0 conformant XML. For example
  31. // it does not report errors with related to the following constraints:
  32. // - atom:entry elements MUST NOT contain more than one atom:link
  33. // element with a rel attribute value of "alternate" that has the
  34. // same combination of type and hreflang attribute values.
  35. // - atom:entry elements that contain no child atom:content element
  36. // MUST contain at least one atom:link element with a rel attribute
  37. // value of "alternate".
  38. //
  39. using System;
  40. using System.Collections.Generic;
  41. using System.Collections.ObjectModel;
  42. using System.Globalization;
  43. using System.IO;
  44. using System.Runtime.Serialization;
  45. using System.Text;
  46. using System.Xml;
  47. using System.Xml.Schema;
  48. using System.Xml.Serialization;
  49. namespace System.ServiceModel.Syndication
  50. {
  51. [XmlRoot ("entry", Namespace = "http://www.w3.org/2005/Atom")]
  52. public class Atom10ItemFormatter : SyndicationItemFormatter, IXmlSerializable
  53. {
  54. const string AtomNamespace ="http://www.w3.org/2005/Atom";
  55. bool preserve_att_ext = true, preserve_elem_ext = true;
  56. Type item_type;
  57. public Atom10ItemFormatter ()
  58. {
  59. }
  60. public Atom10ItemFormatter (SyndicationItem feedToWrite)
  61. : base (feedToWrite)
  62. {
  63. }
  64. public Atom10ItemFormatter (Type itemTypeToCreate)
  65. {
  66. if (itemTypeToCreate == null)
  67. throw new ArgumentNullException ("itemTypeToCreate");
  68. item_type = itemTypeToCreate;
  69. }
  70. protected Type ItemType {
  71. get { return item_type; }
  72. }
  73. public bool PreserveAttributeExtensions {
  74. get { return preserve_att_ext; }
  75. set { preserve_att_ext = value; }
  76. }
  77. public bool PreserveElementExtensions {
  78. get { return preserve_elem_ext; }
  79. set { preserve_elem_ext = value; }
  80. }
  81. public override string Version {
  82. get { return "Atom10"; }
  83. }
  84. protected override SyndicationItem CreateItemInstance ()
  85. {
  86. return new SyndicationItem ();
  87. }
  88. public override bool CanRead (XmlReader reader)
  89. {
  90. if (reader == null)
  91. throw new ArgumentNullException ("reader");
  92. reader.MoveToContent ();
  93. return reader.IsStartElement ("entry", AtomNamespace);
  94. }
  95. public override void ReadFrom (XmlReader reader)
  96. {
  97. if (!CanRead (reader))
  98. throw new XmlException (String.Format ("Element '{0}' in namespace '{1}' is not accepted by this syndication formatter", reader.LocalName, reader.NamespaceURI));
  99. ReadXml (reader, true);
  100. }
  101. public override void WriteTo (XmlWriter writer)
  102. {
  103. WriteXml (writer, true);
  104. }
  105. void IXmlSerializable.ReadXml (XmlReader reader)
  106. {
  107. ReadXml (reader, false);
  108. }
  109. void IXmlSerializable.WriteXml (XmlWriter writer)
  110. {
  111. WriteXml (writer, false);
  112. }
  113. XmlSchema IXmlSerializable.GetSchema ()
  114. {
  115. return null;
  116. }
  117. // read
  118. void ReadXml (XmlReader reader, bool fromSerializable)
  119. {
  120. if (reader == null)
  121. throw new ArgumentNullException ("reader");
  122. SetItem (CreateItemInstance ());
  123. reader.MoveToContent ();
  124. if (reader.MoveToFirstAttribute ()) {
  125. do {
  126. if (reader.NamespaceURI == "http://www.w3.org/2000/xmlns/")
  127. continue;
  128. if (!TryParseAttribute (reader.LocalName, reader.NamespaceURI, reader.Value, Item, Version) && PreserveAttributeExtensions)
  129. Item.AttributeExtensions.Add (new XmlQualifiedName (reader.LocalName, reader.NamespaceURI), reader.Value);
  130. } while (reader.MoveToNextAttribute ());
  131. }
  132. reader.ReadStartElement ();
  133. for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
  134. if (reader.NodeType != XmlNodeType.Element)
  135. throw new XmlException ("Only element node is expected under 'entry' element");
  136. if (reader.NamespaceURI == AtomNamespace)
  137. switch (reader.LocalName) {
  138. case "author":
  139. SyndicationPerson p = Item.CreatePerson ();
  140. ReadPerson (reader, p);
  141. Item.Authors.Add (p);
  142. continue;
  143. case "category":
  144. SyndicationCategory c = Item.CreateCategory ();
  145. ReadCategory (reader, c);
  146. Item.Categories.Add (c);
  147. continue;
  148. case "contributor":
  149. p = Item.CreatePerson ();
  150. ReadPerson (reader, p);
  151. Item.Contributors.Add (p);
  152. continue;
  153. case "id":
  154. Item.Id = reader.ReadElementContentAsString ();
  155. continue;
  156. case "link":
  157. SyndicationLink l = Item.CreateLink ();
  158. ReadLink (reader, l);
  159. Item.Links.Add (l);
  160. continue;
  161. case "published":
  162. Item.PublishDate = XmlConvert.ToDateTimeOffset (reader.ReadElementContentAsString ());
  163. continue;
  164. case "rights":
  165. Item.Copyright = ReadTextSyndicationContent (reader);
  166. continue;
  167. case "source":
  168. Item.SourceFeed = ReadSourceFeed (reader);
  169. continue;
  170. case "summary":
  171. Item.Summary = ReadTextSyndicationContent (reader);
  172. continue;
  173. case "title":
  174. Item.Title = ReadTextSyndicationContent (reader);
  175. continue;
  176. case "updated":
  177. Item.LastUpdatedTime = XmlConvert.ToDateTimeOffset (reader.ReadElementContentAsString ());
  178. continue;
  179. // Atom 1.0 does not specify "content" element, but it is required to distinguish Content property from extension elements.
  180. case "content":
  181. if (reader.GetAttribute ("src") != null) {
  182. Item.Content = new UrlSyndicationContent (CreateUri (reader.GetAttribute ("src")), reader.GetAttribute ("type"));
  183. reader.Skip ();
  184. continue;
  185. }
  186. switch (reader.GetAttribute ("type")) {
  187. case "text":
  188. case "html":
  189. case "xhtml":
  190. Item.Content = ReadTextSyndicationContent (reader);
  191. continue;
  192. default:
  193. SyndicationContent content;
  194. if (!TryParseContent (reader, Item, reader.GetAttribute ("type"), Version, out content))
  195. Item.Content = new XmlSyndicationContent (reader);
  196. continue;
  197. }
  198. }
  199. if (!TryParseElement (reader, Item, Version)) {
  200. if (PreserveElementExtensions)
  201. // FIXME: what to specify for maxExtensionSize
  202. LoadElementExtensions (reader, Item, int.MaxValue);
  203. else
  204. reader.Skip ();
  205. }
  206. }
  207. reader.ReadEndElement (); // </item>
  208. }
  209. TextSyndicationContent ReadTextSyndicationContent (XmlReader reader)
  210. {
  211. TextSyndicationContentKind kind = TextSyndicationContentKind.Plaintext;
  212. switch (reader.GetAttribute ("type")) {
  213. case "html":
  214. kind = TextSyndicationContentKind.Html;
  215. break;
  216. case "xhtml":
  217. kind = TextSyndicationContentKind.XHtml;
  218. break;
  219. }
  220. string text = reader.ReadElementContentAsString ();
  221. TextSyndicationContent t = new TextSyndicationContent (text, kind);
  222. return t;
  223. }
  224. void ReadCategory (XmlReader reader, SyndicationCategory category)
  225. {
  226. if (reader.MoveToFirstAttribute ()) {
  227. do {
  228. if (reader.NamespaceURI == "http://www.w3.org/2000/xmlns/")
  229. continue;
  230. if (reader.NamespaceURI == String.Empty) {
  231. switch (reader.LocalName) {
  232. case "term":
  233. category.Name = reader.Value;
  234. continue;
  235. case "scheme":
  236. category.Scheme = reader.Value;
  237. continue;
  238. case "label":
  239. category.Label = reader.Value;
  240. continue;
  241. }
  242. }
  243. if (!TryParseAttribute (reader.LocalName, reader.NamespaceURI, reader.Value, category, Version) && PreserveAttributeExtensions)
  244. category.AttributeExtensions.Add (new XmlQualifiedName (reader.LocalName, reader.NamespaceURI), reader.Value);
  245. } while (reader.MoveToNextAttribute ());
  246. reader.MoveToElement ();
  247. }
  248. if (!reader.IsEmptyElement) {
  249. reader.Read ();
  250. for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
  251. if (!TryParseElement (reader, category, Version)) {
  252. if (PreserveElementExtensions)
  253. // FIXME: what should be used for maxExtenswionSize
  254. LoadElementExtensions (reader, category, int.MaxValue);
  255. else
  256. reader.Skip ();
  257. }
  258. }
  259. }
  260. reader.Read (); // </category> or <category ... />
  261. }
  262. void ReadLink (XmlReader reader, SyndicationLink link)
  263. {
  264. if (reader.MoveToFirstAttribute ()) {
  265. do {
  266. if (reader.NamespaceURI == "http://www.w3.org/2000/xmlns/")
  267. continue;
  268. if (reader.NamespaceURI == String.Empty) {
  269. switch (reader.LocalName) {
  270. case "href":
  271. link.Uri = CreateUri (reader.Value);
  272. continue;
  273. case "rel":
  274. link.RelationshipType = reader.Value;
  275. continue;
  276. case "type":
  277. link.MediaType = reader.Value;
  278. continue;
  279. case "length":
  280. link.Length = XmlConvert.ToInt64 (reader.Value);
  281. continue;
  282. case "title":
  283. link.Title = reader.Value;
  284. continue;
  285. }
  286. }
  287. if (!TryParseAttribute (reader.LocalName, reader.NamespaceURI, reader.Value, link, Version) && PreserveAttributeExtensions)
  288. link.AttributeExtensions.Add (new XmlQualifiedName (reader.LocalName, reader.NamespaceURI), reader.Value);
  289. } while (reader.MoveToNextAttribute ());
  290. reader.MoveToElement ();
  291. }
  292. if (!reader.IsEmptyElement) {
  293. reader.Read ();
  294. for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
  295. if (!TryParseElement (reader, link, Version)) {
  296. if (PreserveElementExtensions)
  297. // FIXME: what should be used for maxExtenswionSize
  298. LoadElementExtensions (reader, link, int.MaxValue);
  299. else
  300. reader.Skip ();
  301. }
  302. }
  303. }
  304. reader.Read (); // </link> or <link ... />
  305. }
  306. void ReadPerson (XmlReader reader, SyndicationPerson person)
  307. {
  308. if (reader.MoveToFirstAttribute ()) {
  309. do {
  310. if (reader.NamespaceURI == "http://www.w3.org/2000/xmlns/")
  311. continue;
  312. if (!TryParseAttribute (reader.LocalName, reader.NamespaceURI, reader.Value, person, Version) && PreserveAttributeExtensions)
  313. person.AttributeExtensions.Add (new XmlQualifiedName (reader.LocalName, reader.NamespaceURI), reader.Value);
  314. } while (reader.MoveToNextAttribute ());
  315. reader.MoveToElement ();
  316. }
  317. if (!reader.IsEmptyElement) {
  318. reader.Read ();
  319. for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
  320. if (reader.NodeType == XmlNodeType.Element && reader.NamespaceURI == AtomNamespace) {
  321. switch (reader.LocalName) {
  322. case "name":
  323. person.Name = reader.ReadElementContentAsString ();
  324. continue;
  325. case "uri":
  326. person.Uri = reader.ReadElementContentAsString ();
  327. continue;
  328. case "email":
  329. person.Email = reader.ReadElementContentAsString ();
  330. continue;
  331. }
  332. }
  333. if (!TryParseElement (reader, person, Version)) {
  334. if (PreserveElementExtensions)
  335. // FIXME: what should be used for maxExtenswionSize
  336. LoadElementExtensions (reader, person, int.MaxValue);
  337. else
  338. reader.Skip ();
  339. }
  340. }
  341. }
  342. reader.Read (); // end element or empty element
  343. }
  344. SyndicationFeed ReadSourceFeed (XmlReader reader)
  345. {
  346. SyndicationFeed feed = null;
  347. if (!reader.IsEmptyElement) {
  348. reader.Read ();
  349. Atom10FeedFormatter ff = new Atom10FeedFormatter ();
  350. ff.ReadFrom (reader);
  351. feed = ff.Feed;
  352. }
  353. else
  354. feed = new SyndicationFeed ();
  355. reader.Read (); // </source> or <source ... />
  356. return feed;
  357. }
  358. Uri CreateUri (string uri)
  359. {
  360. return new Uri (uri, UriKind.RelativeOrAbsolute);
  361. }
  362. // write
  363. void WriteXml (XmlWriter writer, bool writeRoot)
  364. {
  365. if (writer == null)
  366. throw new ArgumentNullException ("writer");
  367. if (Item == null)
  368. throw new InvalidOperationException ("Syndication item must be set before writing");
  369. if (writeRoot)
  370. writer.WriteStartElement ("entry", AtomNamespace);
  371. if (Item.BaseUri != null)
  372. writer.WriteAttributeString ("xml:base", Item.BaseUri.ToString ());
  373. // atom:entry elements MUST contain exactly one atom:id element.
  374. writer.WriteElementString ("id", AtomNamespace, Item.Id ?? new UniqueId ().ToString ());
  375. // atom:entry elements MUST contain exactly one atom:title element.
  376. (Item.Title ?? new TextSyndicationContent (String.Empty)).WriteTo (writer, "title", AtomNamespace);
  377. if (Item.Summary != null)
  378. Item.Summary.WriteTo (writer, "summary", AtomNamespace);
  379. if (!Item.PublishDate.Equals (default (DateTimeOffset))) {
  380. writer.WriteStartElement ("published");
  381. // FIXME: use DateTimeOffset itself once it is implemented.
  382. writer.WriteString (XmlConvert.ToString (Item.PublishDate.UtcDateTime, XmlDateTimeSerializationMode.RoundtripKind));
  383. writer.WriteEndElement ();
  384. }
  385. // atom:entry elements MUST contain exactly one atom:updated element.
  386. writer.WriteStartElement ("updated", AtomNamespace);
  387. // FIXME: use DateTimeOffset itself once it is implemented.
  388. writer.WriteString (XmlConvert.ToString (Item.LastUpdatedTime.UtcDateTime, XmlDateTimeSerializationMode.RoundtripKind));
  389. writer.WriteEndElement ();
  390. foreach (SyndicationPerson author in Item.Authors)
  391. if (author != null) {
  392. writer.WriteStartElement ("author", AtomNamespace);
  393. WriteAttributeExtensions (writer, author, Version);
  394. writer.WriteElementString ("name", AtomNamespace, author.Name);
  395. writer.WriteElementString ("uri", AtomNamespace, author.Uri);
  396. writer.WriteElementString ("email", AtomNamespace, author.Email);
  397. WriteElementExtensions (writer, author, Version);
  398. writer.WriteEndElement ();
  399. }
  400. foreach (SyndicationPerson contributor in Item.Contributors) {
  401. if (contributor != null) {
  402. writer.WriteStartElement ("contributor", AtomNamespace);
  403. WriteAttributeExtensions (writer, contributor, Version);
  404. writer.WriteElementString ("name", AtomNamespace, contributor.Name);
  405. writer.WriteElementString ("uri", AtomNamespace, contributor.Uri);
  406. writer.WriteElementString ("email", AtomNamespace, contributor.Email);
  407. WriteElementExtensions (writer, contributor, Version);
  408. writer.WriteEndElement ();
  409. }
  410. }
  411. foreach (SyndicationCategory category in Item.Categories)
  412. if (category != null) {
  413. writer.WriteStartElement ("category", AtomNamespace);
  414. if (category.Name != null)
  415. writer.WriteAttributeString ("term", category.Name);
  416. if (category.Label != null)
  417. writer.WriteAttributeString ("label", category.Label);
  418. if (category.Scheme != null)
  419. writer.WriteAttributeString ("scheme", category.Scheme);
  420. WriteAttributeExtensions (writer, category, Version);
  421. WriteElementExtensions (writer, category, Version);
  422. writer.WriteEndElement ();
  423. }
  424. foreach (SyndicationLink link in Item.Links)
  425. if (link != null) {
  426. writer.WriteStartElement ("link");
  427. if (link.RelationshipType != null)
  428. writer.WriteAttributeString ("rel", link.RelationshipType);
  429. if (link.MediaType != null)
  430. writer.WriteAttributeString ("type", link.MediaType);
  431. if (link.Title != null)
  432. writer.WriteAttributeString ("title", link.Title);
  433. if (link.Length != 0)
  434. writer.WriteAttributeString ("length", link.Length.ToString (CultureInfo.InvariantCulture));
  435. writer.WriteAttributeString ("href", link.Uri != null ? link.Uri.ToString () : String.Empty);
  436. WriteAttributeExtensions (writer, link, Version);
  437. WriteElementExtensions (writer, link, Version);
  438. writer.WriteEndElement ();
  439. }
  440. if (Item.Content != null)
  441. Item.Content.WriteTo (writer, "content", AtomNamespace);
  442. if (Item.Copyright != null)
  443. Item.Copyright.WriteTo (writer, "rights", AtomNamespace);
  444. if (Item.SourceFeed != null) {
  445. writer.WriteStartElement ("source", AtomNamespace);
  446. Item.SourceFeed.SaveAsAtom10 (writer);
  447. writer.WriteEndElement ();
  448. }
  449. if (writeRoot)
  450. writer.WriteEndElement ();
  451. }
  452. }
  453. }