import java.util.Enumeration;
import org.xml.sax.*;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.AttributesImpl;
import RssChannel.RssItem;
interface RssHandler {
void channelUpdate (RssChannel c) throws SAXException;
}
/**
* Marshaling RSS Data to SAX Events
*/
public class RssProducer implements RssHandler
{
private static char lineEnd [] = { '\n', '\t', '\t', '\t' };
private ContentHandler content;
private LexicalHandler lexical;
public RssProducer (ContentHandler n)
{ content = n; }
public void setLexicalHandler (LexicalHandler l)
{ lexical = l; }
private void doIndent (int n)
throws SAXException
{
n++; // NL
if (n > lineEnd.length)
n = lineEnd.length;
content.ignorableWhitespace (lineEnd, 0, n);
}
private void element (int indent, String name, String val, Attributes atts)
throws SAXException
{
char contents [] = val.toCharArray ();
doIndent (indent);
content.startElement ("", "", name, atts);
content.characters (contents, 0, contents.length);
content.endElement ("", "", name);
}
public void channelUpdate (RssChannel channel)
throws SAXException
{
AttributesImpl atts = new AttributesImpl ();
content.startDocument ();
if (lexical != null) {
lexical.startDTD ("rss",
"-//Netscape Communications//DTD RSS 0.91//EN",
"http://my.netscape.com/publish/formats/rss-0.91.dtd");
lexical.endDTD ();
}
atts.addAttribute ("", "", "version", "CDATA", "0.91");
content.startElement ("", "", "rss", atts);
atts.clear ();
doIndent (0);
content.startElement ("", "", "channel", atts);
// describe the channel
// four required elements
element (1, "title", channel.title, atts);
element (1, "link", channel.link, atts);
element (1, "description", channel.description, atts);
element (1, "language", channel.language, atts);
// optional elements
if ("" != channel.managingEditor)
element (1, "managingEditor", channel.managingEditor, atts);
if ("" != channel.webMaster)
element (1, "webMaster", channel.webMaster, atts);
// ... and many others, notably image/icon and text input
// channel contents: at least one item
for (Enumeration e = channel.items.elements ();
e.hasMoreElements ();
/**/) {
RssItem item = (RssItem) e.nextElement ();
doIndent (1);
content.startElement ("", "", "item", atts);
if ("" != item.title)
element (2, "title", item.title, atts);
if ("" != item.link)
element (2, "link", item.link, atts);
if ("" != item.description)
element (2, "description", item.description, atts);
doIndent (1);
content.endElement ("", "", "item");
}
content.endElement ("", "", "channel");
content.endElement ("", "", "rss");
content.endDocument ();
}
}
|