[java] RSS-뉴스 읽기

다음 뉴스 RSS [ http://media.daum.net/rss/today/primary/all/rss2.xml ]

--------[ source code ]-------------
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class GetRSS {

/**
* @param args
*/
public static void main(String[] args) {
String rssUrl = "http://media.daum.net/rss/today/primary/all/rss2.xml";

try {
parseXml(rssUrl);
} catch (Exception e) {
e.printStackTrace();
}
}



private static void parseXml(String _url) throws Exception{
System.out.println("parse XML");

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(_url);

doc.getDocumentElement().normalize();

NodeList itemNodeList = doc.getElementsByTagName("item");

System.out.println("count :"  + itemNodeList.getLength());
for(int i =0; i < itemNodeList.getLength(); i++){
Node itemNode = itemNodeList.item(i);

if(itemNode.getNodeType() == Node.ELEMENT_NODE){
Element itemElement = (Element)itemNode;

NodeList titleNodeList = itemElement.getElementsByTagName("title");
   Element titleElement = (Element)titleNodeList.item(0);
   NodeList childTitleNodeList = titleElement.getChildNodes();
   System.out.printf("[title : %s]\n", ((Node)childTitleNodeList.item(0)).getNodeValue());
   
   NodeList linkNodeList = itemElement.getElementsByTagName("link");
   Element linkElement = (Element) linkNodeList.item(0);
   NodeList childLinkNodeList = linkElement.getChildNodes();
   System.out.printf("[link : %s]\n", ((Node)childLinkNodeList.item(0)).getNodeValue());
 
   NodeList pubDate = itemElement.getElementsByTagName("pubDate");
   Element pubDateElement = (Element)pubDate.item(0);
   NodeList childPubDateNodeList = pubDateElement.getChildNodes();
   System.out.printf("[pub-date : %s]\n", ((Node)childPubDateNodeList.item(0)).getNodeValue());
 
   NodeList createDate = itemElement.getElementsByTagName("dc:creator");
   Element createElement = (Element)createDate.item(0);
   NodeList childCreateNodeList = createElement.getChildNodes();
   System.out.printf("[creator : %s]\n", ((Node)childCreateNodeList.item(0)).getNodeValue());
}
}
}

}


댓글

이 블로그의 인기 게시물

한반도 왕 연대표 2.2 update