XML 파싱 예제

개발/프로그래밍2007. 10. 16. 15:15
728x90

import javax.xml.parsers.*;
import org.w3c.dom.*;

/**
 *
 *  * @author 일퍼센트
 *
 */
class domparse
{
 public static void main(String[] args)
 {
  try{
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

     //    DocumentBuilder는 생성자가 protect이다.
     DocumentBuilder builder = factory.newDocumentBuilder();

     // xml문서를 분석해서 tree형태로 메모리에 올린다. document interface를 리턴한다.
     Document xmlDoc = builder.parse("http://codezip.tistory.com/rss");
 
     Element root = xmlDoc.getDocumentElement();
     NodeList list = root.getElementsByTagName("item");
        for(int i=0; i<list.getLength();i++){
      
       Element element = (Element)list.item(i);
       System.out.println("=====" + getData1(element, "title"));
       System.out.println("=====" + getData1(element, "link"));
     //  System.out.println("=====" + getData(element, "")
      }
          
    }catch(Exception e)
    {
   e.printStackTrace(System.err);
    }

 }

public static String getData1(Element element, String tagName){
 NodeList list = element.getElementsByTagName(tagName);
 Element cElement = (Element)list.item(0);
 
 if(cElement.getFirstChild()!=null){
  return cElement.getFirstChild().getNodeValue();
 }else{
  return "";
 
 }
}

}

}

[DocumentBuilder]
 
method
return
explain
newDocument()
Document
새로운 DOM Document 객체를 생성
Parse()
Document
Parsing 작업 시작
 
 
 
 

[DocumentBuilderFactory]

Meothd

Return

Explain

newDocumentBuilder

 DocumentBuilder

새로운 DocumentBuilder객체를 생성함

newInstance

DocumentBuilderFactory

새로운 DocumentBuilderFactory

객체를 생성

 

 

 

 

[Element]

 

Meothd

Return

Explain

getDocumentElement

 

Element

 

자식 노드에의 직접 액세스를

가능하게 하는 편리한 속성

getTagName

String

Tag 이름

getElementsByTagName

NodeList

자식 Elements Nodelist를 리턴

 

getFirstChild               Node           최초 자식 노드

getNodeValue                String         노드의 값

 

728x90

작성자

Posted by 일퍼센트

관련 글

댓글 영역