IT/Java & JSP & FW

java :: DOM 파서를 이용한 XML 호출 (재귀호출방식)

엑수시아 2012. 10. 31. 00:27

회사에서 XML 을 파싱해야 하는데, 해본적이 없어서.. -_-;; 난감...

무튼 가장 간단하고 모든 트리를 재귀호출로 탐사하는 방식으로 하나 짜봤습니다..

제길.. 6시 5분에 일어나야 하는데 지금 시간이 오후 12시 25분..ㅜㅜㅜㅜ


그대로 복사하셔서 사용하시면 원리파악이 되실껍니다~! 그럼 이만.. 자야겠어요!!


<네이버 최신 뉴스 DOM 계층 이용 XML출력(재귀호출방식) >

package XMLpasing;

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 XMLDOMtest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		try {
			XMLDOMdata("http://feeds.feedburner.com/naver_news_popular");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void XMLDOMdata(String url) throws Exception{
		
		DocumentBuilder builder;
		DocumentBuilderFactory factory;
		Document document;
		
		factory = DocumentBuilderFactory.newInstance();
		builder = factory.newDocumentBuilder();
		document = builder.parse(url);
		document.getDocumentElement().normalize();
		
		NodeList nodeList = document.getElementsByTagName("*");
		int count = nodeList.getLength();
		
		findNode(nodeList, count);
		
		System.out.println("끝");
	}
	
	public static void findNode(NodeList nodeList, int length)throws Exception{
		
		for(int i = 0 ; i<length ; i++){
			Node node = nodeList.item(i);
			if(node.getNodeType() == Node.ELEMENT_NODE){
				Element element = (Element)node;
				
				if(element.hasChildNodes()){
					NodeList childNodeList = element.getElementsByTagName("*");
					int childLength = childNodeList.getLength();
//					Node childNode = childNodeList.item(i);
					
					findNode(childNodeList, childLength);

				}
				System.out.println(node.getNodeName());
				System.out.println(":"+node.getTextContent());
			}
		}
	}
}