Writing RSS and Atom


Writing RSS or Atom is definitely easier than reading it. All you need to do is decide on the flavor you'd like to output and stick with it, validating as you go. The prime reasons feeds fail to validate are that users have neglected to ensure that dates are in correct format and all additional namespaces are included in the feed. Even enclosures or other more advanced features are fairly easy to add to feeds.

Writing with .NET

Writing RSS or Atom with .NET is easiest with the XmlWriter class. It provides methods for adding attributes and child elements, and it can write to either files or streams. Listings 18-9 and 18-10 show the extensions to the RssFeed and RssEntry classes to include saving RSS feeds.

Listing 18-9: Writing RSS 2.0 with XmlWriter

image from book
      public void Save(string filename) {          XmlWriter writer = null;          XmlWriterSettings settings = new XmlWriterSettings();          settings.CheckCharacters = true;          settings.CloseOutput = true;          settings.Encoding = Encoding.UTF8;          writer = XmlWriter.Create(filename, settings);          this.Save(writer);      }      public void Save(System.IO.Stream outputStream) {          XmlWriter writer = null;          XmlWriterSettings settings = new XmlWriterSettings();          settings.CheckCharacters = true;          settings.CloseOutput = true;          settings.Encoding = Encoding.UTF8;          writer = XmlWriter.Create(outputStream, settings);          this.Save(writer);      }      public void Save(System.Xml.XmlWriter outputWriter) {          outputWriter.WriteStartDocument();          outputWriter.WriteStartElement("rss");          outputWriter.WriteAttributeString("version", "2.0");          outputWriter.WriteStartElement("channel");          outputWriter.WriteElementString("title", this.Title);          outputWriter.WriteElementString("link", this.Link);          outputWriter.WriteElementString("description", this.Description);          outputWriter.WriteElementString("language", this.Language);          outputWriter.WriteElementString("copyright", this.Copyright);          outputWriter.WriteElementString("managingEditor", this.ManagingEditor);          outputWriter.WriteElementString("pubDate", this.PubDate);          foreach (RssEntry entry in this.Entries) {              entry.Save(outputWriter);          }          outputWriter.WriteEndElement();      //channel          outputWriter.WriteEndElement();     //rss          outputWriter.WriteEndDocument();          outputWriter.Close();      } 
image from book

The three overloaded methods provide the user of the RssFeed class with flexibility when saving the output. However, the first two delegate to the third that creates the RSS using the XmlWriter class. Creating XML using the XmlWriter can sometimes feel a little repetitive, because you are repeatedly calling the various WriteXXX methods. However, this is preferable (in my opinion) to using the classes of the XML DOM to build up the structure in memory. Remember to close the XmlWriter or call Flush() to ensure the content is actually written.

Listing 18-10: Writing RSS 2.0 items with XmlWriter

image from book
      public void Save(System.Xml.XmlWriter outputWriter) {          outputWriter.WriteStartElement("item");          outputWriter.WriteElementString("title", this.Title);          outputWriter.WriteElementString("link", this.Link);          outputWriter.WriteElementString("description", this.Description);          outputWriter.WriteEndElement();     //item      } 
image from book

Writing with Java

Choices for writing RSS or Atom with Java are slightly more limited. Using only the core J2SE class library, your best choice is the DOM. Other libraries exist to make it easier, such as StAX, JDOM, or even serializing to and from Java objects. Listing 18-11 shows creating an RSS 2.0 document using the DOM.

Listing 18-11: Writing RSS 2.0 with DOM

image from book
      package com.wrox.proxml;      import java.io.*;      import javax.xml.*;      import javax.xml.parsers.*;      import javax.xml.transform.*;      import javax.xml.transform.dom.DOMSource;      import javax.xml.transform.stream.StreamResult;      import org.w3c.dom.*;      public class RSSWriter {          Document doc;          Element  channel;          public RSSWriter() {              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();              try {                  DocumentBuilder builder = factory.newDocumentBuilder();                  doc = builder.newDocument();                  Element rss = doc.createElement("rss");                  rss.setAttribute("version", "2.0");                  doc.appendChild(rss);                  channel = doc.createElement("channel");                  rss.appendChild(channel);              } catch (Exception ex){                  ex.printStackTrace();              }          }          public void setFeedTitle(String title){              this.addElement(channel, "title", title);          }          public void setFeedLink(String link) {              this.addElement(channel, "link", link);          }          public void setFeedDescription(String description){              this.addElement(channel, "description", description);          }          public Element addItem(String title, String link, String desc){              Element item = doc.createElement("item");              addElement(item, "title", title);              addElement(item, "link", link);              addElement(item, "description", desc);              addElement(item, "guid", link).setAttribute("isPermaLink", "false");              channel.appendChild(item);              return item;          }          public void Save(OutputStream out){              try {                  Transformer transformer =                  TransformerFactory.newInstance().newTransformer(  );                  Source source = new DOMSource( doc );                  Result output = new StreamResult( out );                  transformer.transform( source, output );              } catch (TransformerException tex) {                  tex.printStackTrace();              }          }          private Element addElement(Element parent, String name, String value){              Element el = doc.createElement(name);              el.setTextContent(value);              parent.appendChild(el);              return el;          }          public static void main(String[] args) {              RSSWriter writer = new RSSWriter();              writer.setFeedTitle("Test feed");              writer.setFeedLink("http://www.example.com");              writer.setFeedDescription("Sample RSS 2.0 feed");              writer.addItem("Item 1",                     "http://www.example.com/1",                     "Some more lengthy description of item 1");              writer.addItem("Item 2",                     "http://www.example.com/2",                     "Description of the second item");              writer.Save(System.out);          }      } 
image from book

The DOM makes it easy to create and manipulate XML documents. The only mistake users make when working with the DOM is to forget to appendChild when adding elements to the DOM. For this reason, and to reduce repetition in the code, I'll usually create one or more addElement methods as shown in the preceding sample. This encapsulates the creation of the element and appends the new element at the appropriate location in the document.

Class Libraries Available for Processing RSS and Atom

Rather than process the RSS with the XML functionality natively, you may want to use an RSS parsing library. Generally, these hide many of the ambiguities in the different feed types and make your life a little easier. Some of the more notable RSS parsing libraries are:

  • q RSS.NET ( http://www.rssdotnet.com/ )-Library for RSS 2.0 feeds for .NET.

  • q My.Blogs ( http://www.msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvs05/html/MyBlogsGetStart.asp )-A library for parsing and creating RSS 1.0, RSS 2.0 and Atom feeds. Written in and designed for Visual Basic 2005 developers.

  • q Rome ( http://www.wiki.java.net/bin/view/Javawsxml/Rome )-A Java library for processing RSS 1.0, 2.0 and Atom feeds (as well as a few more arcane versions, such as both versions of 0.91). This library also supports extensions to add parsing for additional namespaces.

  • q RSSLib4J ( http://www.sourceforge.net/projects/rsslib4j/ )-Library for processing RSS 1.0 and 2.0 feeds in Java.

  • q Atom.NET ( http://www.atomnet.sourceforge.net/ )-Library for processing Atom feeds with .NET. Sadly, this library is still not 1.0 compliant.




Professional XML
Professional XML (Programmer to Programmer)
ISBN: 0471777773
EAN: 2147483647
Year: 2004
Pages: 215

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net