How Read data from web site

16 views
Skip to first unread message

asanka ishara

unread,
Apr 29, 2012, 4:02:43 AM4/29/12
to mChoice Developer
Hi everyone,
When you are creating applications in appzone you may need to read
data from out side.Most of the cases you may need to read data
available in website.If the website has RSS feed then the solution is
very simple.If not you must read the content using string buffer. But
read the content is not a good solution.because if the website content
structure change it will affect on you'r application. Here i'm going
to describe how to use RSS feed.

--first import the packages which is needed

import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

--- Now i'm going to create my "RSSReader" class
--- It will read the RSS contet by using Tags.You can provide RSS url
and read the tag on it.

public class RSSReader {
private static RSSReader instance = null;
private RSSReader() {
}
public static RSSReader getInstance() {
if(instance == null)
instance = new RSSReader();
return instance;
}
public void writeNews() {
try {
DocumentBuilder builder =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
URL u = new URL("http://www.espncricinfo.com/rss/content/story/feeds/
8.xml"); // your feed url
Document doc = builder.parse(u.openStream());
NodeList nodes = doc.getElementsByTagName("item");//this is the tag
name,which will read
//the content of that tag
for(int i=0;i<nodes.getLength();i++) {
Element element = (Element)nodes.item(i);
System.out.println("RSS readed Title: " +
getElementValue(element,"title"));
System.out.println();
}//for
}//try
catch(Exception ex) {
ex.printStackTrace();
}
}
private String getCharacterDataFromElement(Element e) {
try {
Node child = e.getFirstChild();
if(child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
}catch(Exception ex) {

}
return "";
} //private String getCharacterDataFromElement
protected float getFloat(String value) {
if(value != null && !value.equals(""))
return Float.parseFloat(value);
else
return 0;
}
protected String getElementValue(Element parent,String label) {
return
getCharacterDataFromElement((Element)parent.getElementsByTagName(label).item(0));
}
public static void main(String[] args) {
RSSReader reader = RSSReader.getInstance();
reader.writeNews();
}
}

-- now you can simply run the main method.Then you will see the RSS
feed comes to you'r application.

hope you will enjoy,
--- ishara

Amila Silva

unread,
Apr 29, 2012, 5:17:05 AM4/29/12
to mchoice-...@googlegroups.com
Thanks Ishara,
Very helpful one for developers like us.
--
Thanks!

Cheers
Amila Silva

Reply all
Reply to author
Forward
0 new messages