웹 & 프레임워크

dom control

늘근이 2014. 10. 23. 08:32

DOM은 XML문서를 몽땅 메모리에 올려서 다룬다. 
그에 비하여 SAX 방식은 한줄한줄 읽어나가면서 처리 
(몽땅 메모리에 올리지 않는다.) 
그외에도 여러가지 방식이 있다. 

Document 
    --------   Element (Root Element) 
                ---------- Element 
                            ----- Attr 
                            ----- Text 
                ---------- Element 
                            ----- CDataSection 

--------------------------------------- 

import java.io.File; 

import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 

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


public class XMLExam01 { 

    public static void main(String[] args) throws Exception { 
          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
          DocumentBuilder db = dbf.newDocumentBuilder(); 
          Document doc = db.parse(new File("src/first.xml")); 
          Element rootElement = doc.getDocumentElement(); 
          String name = rootElement.getTextContent(); 
          System.out.println(name); 
    } 



import java.io.File; 

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

    public static void main(String[] args) throws Exception { 
          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
          DocumentBuilder db = dbf.newDocumentBuilder(); 
          Document doc = db.parse(new File("src/first.xml")); 
          Element rootElement = doc.getDocumentElement(); 
//          String name = rootElement.getTextContent(); 
//          System.out.println(name); 
           
          NodeList nodeList = rootElement.getChildNodes(); 
          System.out.println(nodeList.getLength()); 
          for(int i = 0; i < nodeList.getLength(); i++){ 
              Node node = nodeList.item(i); 
              if(node instanceof Element){ 
                  Element e = (Element)node; 
                  System.out.println(e.getTextContent()); 
              } 
          } 
    } 


-------------------------------------------- 

<?xml version="1.0" encoding="UTF-8"?> 
<nameList> 
    <name>kim sungpark</name> 
    <name>kang</name>     
</nameList>