본문 바로가기

Java

RSS XML DOM 파싱

반응형

 

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());
}
}
}

}
 

 

잘썼습니다.

출처-http://ch76.blogspot.kr/2013/07/java-rss.html

반응형

'Java' 카테고리의 다른 글

java & javascript 문자 모든 공백 제거  (0) 2014.06.23
jdk 1.6 다운로드 링크  (0) 2014.04.11
Java? 객체지향언어?  (0) 2013.06.02
표현식과 연산자  (0) 2013.05.28
JVM 메모리구조  (3) 2013.05.28