본문 바로가기

(Before)BitSchool

2014/06/10 XML - xml파서, DOM 수정, 추가, 삭제, SAX 파서

반응형

http://jakarta.apache.org/

 

07.jsp_dom.pdf

 

DOM

-데이터를 검색, 수정, 삭제가 가능

 

 

자바 프로젝트를 만들고 dtd와 xml 파일을 만들어준다.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="euc-kr"?>
 
<!DOCTYPE booklist SYSTEM "bml.dtd">
 
<booklist>
    <book kind="컴퓨터">
        <title>XML 웹 서비스</title>
        <author>신민철</author>
        <publisher>프리렉</publisher>
        <price>20000</price>
    </book>
    <book kind="소설">
        <title>금붕어메세지</title>
        <author>이능문</author>
        <publisher>무한(구)생각과기억</publisher>
        <price>9000</price>
    </book>
    <book kind="컴퓨터">
        <title>Java And XML</title>
        <author>홍길동</author>
        <publisher>영진 출판사</publisher>
        <price>25000</price>
    </book>
</booklist>
 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="euc-kr"?>
 
<!-- 엘리먼트 선언 -->
<!ELEMENT booklist (book*)>
    <!ELEMENT book (title, author+, publisher, price)>
        <!ELEMENT title (#PCDATA)>
        <!ELEMENT author (#PCDATA)>
    <!ELEMENT publisher (#PCDATA)>
        <!ELEMENT price (#PCDATA)>
 
<!-- 속성 선언 -->
<!ATTLIST book 
        id ID #IMPLIED
        kind CDATA #REQUIRED>
 
 
 
 

 

 

Ctrl+Shift+O 를 누르면 자동 import 해줄수 있다.

이중에 org.w3c.dom.Document를 선택한다.

 

 

 

반응형

엘리먼트의 이름을 출력할 수 있다.

 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
 
 
public class GetRootElement {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
            try{
                // DOM 파서 생성
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                
                factory.setIgnoringElementContentWhitespace(true);// 공백 무시
                
                DocumentBuilder builder = factory.newDocumentBuilder();
                
                //XML 문서 파싱
                Document document = builder.parse("bml.xml"); //import org.w3c.dom.Document;
                
                //루트 엘리먼트 객체 얻어오기
                Element rootElement = document.getDocumentElement(); //import org.w3c.dom.Element;
                
                Element firstBookElement = (Element)rootElement.getFirstChild();   // book
                Element titleElement = (Element)firstBookElement.getFirstChild();  // title
                Text titleText = (Text)titleElement.getFirstChild();  // 컨텐츠가 담겨있다.
                String strTitle = titleText.getData();
                
                System.out.println(strTitle);
                
                
            }catch(Exception e){
                e.printStackTrace();
            }
    }
 
}
 

결과값 : XML 웹 서비스

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
 
 
public class GetRootElement {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
            try{
                // DOM 파서 생성
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                
                factory.setIgnoringElementContentWhitespace(true);// 공백 무시
                
                DocumentBuilder builder = factory.newDocumentBuilder();
                
                //XML 문서 파싱
                Document document = builder.parse("bml.xml"); //import org.w3c.dom.Document;
                
                //루트 엘리먼트 객체 얻어오기
                Element rootElement = document.getDocumentElement(); //import org.w3c.dom.Element;
                
                Element firstBookElement = (Element)rootElement.getFirstChild();   // book
                
                String kind = firstBookElement.getAttribute("kind");
                System.out.println("kind==> "+ kind);
                
                Element titleElement = (Element)firstBookElement.getFirstChild();  // title
                Text titleText = (Text)titleElement.getLastChild();  // 컨텐츠가 담겨있다.
                String strTitle = titleText.getData();
                
                System.out.println(strTitle);
                
 
                
            }catch(Exception e){
                e.printStackTrace();
            }
    }
 
}
 

출력값 : kind==> 컴퓨터

XML 웹 서비스

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.io.IOException;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
 
 
public class GetBookTitle {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    
        try{
            // DOM 파서 생성
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            
            factory.setIgnoringElementContentWhitespace(true);// 공백 무시
            
            DocumentBuilder builder = factory.newDocumentBuilder();
            
            //XML 문서 파싱
            Document document = builder.parse("bml.xml"); //import org.w3c.dom.Document;
            
            //루트 엘리먼트 객체 얻어오기
            Element rootElement = document.getDocumentElement(); //import org.w3c.dom.Element;
            
            
            NodeList titleElements = rootElement.getElementsByTagName("title");
            
            for(int i=0;i<titleElements.getLength(); i++){
                Element titleElement = (Element)titleElements.item(i);
                Text titleText = (Text)titleElement.getFirstChild();
                System.out.println(titleText.getData());
            }
            
 
            
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
 
 

결과값 : XML 웹 서비스

금붕어메세지

Java And XML

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
 
 
public class AppendNewBook {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
 
        try{
            // DOM 파서 생성
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            
            factory.setIgnoringElementContentWhitespace(true);// 공백 무시
            
            DocumentBuilder builder = factory.newDocumentBuilder();
            
            //XML 문서 파싱
            Document document = builder.parse("bml.xml"); //import org.w3c.dom.Document;
            
            //루트 엘리먼트 객체 얻어오기
            Element rootElement = document.getDocumentElement(); //import org.w3c.dom.Element;
            
            
            Element bookElement = document.createElement("book");
            
            Element titleElement = document.createElement("title");
            Text titleText = document.createTextNode("시인과 도둑");
            titleElement.appendChild(titleText);  // 연결
            
            Element authorElement = document.createElement("author");
            Text authorText = document.createTextNode("김도둑");
            titleElement.appendChild(authorText);  // 연결
            
            Element publisherElement = document.createElement("publisher");
            Text publisherText = document.createTextNode("시인출판사");
            publisherElement.appendChild(publisherText);  // 연결
            
            Element priceElement = document.createElement("price");
            Text priceText = document.createTextNode("9000");
            priceElement.appendChild(priceText);  // 연결
            
            bookElement.appendChild(titleElement);   // book에 연결
            bookElement.appendChild(authorElement);
            bookElement.appendChild(publisherElement);
            bookElement.appendChild(priceElement);
            
            
            rootElement.appendChild(bookElement);   // root에 연결
            
            NodeList titleElements = rootElement.getElementsByTagName("title");
            for(int i=0;i<titleElements.getLength(); i++){
                Element titleEle = (Element)titleElements.item(i);
                Text titleTex = (Text)titleEle.getFirstChild();
                System.out.println(titleTex.getData());
            }
            
        }catch(Exception e){
            e.printStackTrace();
        }
    }
 
}
 

DOM은 수정, 추가가  가능하다.

 

결과물 : XML 웹 서비스

금붕어메세지

Java And XML

시인과 도둑

 

 

DOM 추가와 삭제

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
 
 
public class AppendNewBook {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
 
        try{
            // DOM 파서 생성
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            
            factory.setIgnoringElementContentWhitespace(true);// 공백 무시
            
            DocumentBuilder builder = factory.newDocumentBuilder();
            
            //XML 문서 파싱
            Document document = builder.parse("bml.xml"); //import org.w3c.dom.Document;
            
            //루트 엘리먼트 객체 얻어오기
            Element rootElement = document.getDocumentElement(); //import org.w3c.dom.Element;
            
            
            Element bookElement = document.createElement("book");
            
            Element titleElement = document.createElement("title");
            Text titleText = document.createTextNode("시인과 도둑");
            titleElement.appendChild(titleText);  // 연결
            
            Element authorElement = document.createElement("author");
            Text authorText = document.createTextNode("김도둑");
            titleElement.appendChild(authorText);  // 연결
            
            Element publisherElement = document.createElement("publisher");
            Text publisherText = document.createTextNode("시인출판사");
            publisherElement.appendChild(publisherText);  // 연결
            
            Element priceElement = document.createElement("price");
            Text priceText = document.createTextNode("9000");
            priceElement.appendChild(priceText);  // 연결
            
            bookElement.appendChild(titleElement);   // book에 연결
            bookElement.appendChild(authorElement);
            bookElement.appendChild(publisherElement);
            bookElement.appendChild(priceElement);
            
            
            rootElement.appendChild(bookElement);   // root에 연결
            
            
            System.out.println("-------------Before---------------");
            NodeList titleElements = rootElement.getElementsByTagName("title");
            for(int i=0;i<titleElements.getLength(); i++){
                Element titleEle = (Element)titleElements.item(i);
                Text titleTex = (Text)titleEle.getFirstChild();
                System.out.println(titleTex.getData());
            }
            
            rootElement.removeChild(bookElement);
            
            System.out.println("-------------After---------------");
            
            for(int i=0;i<titleElements.getLength(); i++){
                Element titleEle = (Element)titleElements.item(i);
                Text titleTex = (Text)titleEle.getFirstChild();
                System.out.println(titleTex.getData());
            }
            
        }catch(Exception e){
            e.printStackTrace();
        }
    }
 
}
 

결과값 : -------------Before---------------

XML 웹 서비스

금붕어메세지

Java And XML

시인과 도둑

-------------After---------------

XML 웹 서비스

금붕어메세지

Java And XML

 

 

 

자동으로 메소드 만들기

 

만들고자하는 부분을 마우스로 블록잡고 오른쪽 클릭 

Extract Method

 

 

 

After 부분에 같은 내용이 있어 쓰레기 값이 생기는 현상이 있다.

 

 

 

 

 

그럴경우 밑에 부분을 지우고 나서 다시 블록을 잡고 실행해준다.

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
 
 
public class AppendNewBook {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
 
        try{
            // DOM 파서 생성
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            
            factory.setIgnoringElementContentWhitespace(true);// 공백 무시
            
            DocumentBuilder builder = factory.newDocumentBuilder();
            
            //XML 문서 파싱
            Document document = builder.parse("bml.xml"); //import org.w3c.dom.Document;
            
            //루트 엘리먼트 객체 얻어오기
            Element rootElement = document.getDocumentElement(); //import org.w3c.dom.Element;
            
            
            Element bookElement = document.createElement("book");
            
            Element titleElement = document.createElement("title");
            Text titleText = document.createTextNode("시인과 도둑");
            titleElement.appendChild(titleText);  // 연결
            
            Element authorElement = document.createElement("author");
            Text authorText = document.createTextNode("김도둑");
            titleElement.appendChild(authorText);  // 연결
            
            Element publisherElement = document.createElement("publisher");
            Text publisherText = document.createTextNode("시인출판사");
            publisherElement.appendChild(publisherText);  // 연결
            
            Element priceElement = document.createElement("price");
            Text priceText = document.createTextNode("9000");
            priceElement.appendChild(priceText);  // 연결
            
            bookElement.appendChild(titleElement);   // book에 연결
            bookElement.appendChild(authorElement);
            bookElement.appendChild(publisherElement);
            bookElement.appendChild(priceElement);
            
            
            rootElement.appendChild(bookElement);   // root에 연결
            
            
            System.out.println("-------------Before---------------");
            getContents(rootElement);
            
            rootElement.removeChild(bookElement);
            
            System.out.println("-------------After---------------");
            getContents(rootElement);
            
            
        }catch(Exception e){
            e.printStackTrace();
        }
    }
 
    private static void getContents(Element rootElement) {
        NodeList titleElements = rootElement.getElementsByTagName("title");
        for(int i=0;i<titleElements.getLength(); i++){
            Element titleEle = (Element)titleElements.item(i);
            Text titleTex = (Text)titleEle.getFirstChild();
            System.out.println(titleTex.getData());
        }
    }
 
}
 

 

 

 

SAX 파서 

- 처음부터 끝까지 읽어 내려가면서 이벤트 발생 방식의 파서

- 오직 읽기와 쓰기만 가능하다. 

 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 
 
import org.xml.sax.*;
 
public class MyContentHandler implements ContentHandler {
 
    public void setDocumentLocator(Locator locator) {}
    public void startDocument() throws SAXException {}
    public void endDocument() throws SAXException {}
    public void startPrefixMapping(String prefix, String uri) throws SAXException {}
    public void endPrefixMapping(String prefix) throws SAXException {}
 
    // 시작 태그를 만났을 때 발생하는 이벤트를 처리하는 메소드
    public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
        if(qName.equals("booklist")) {
            System.out.println(qName);
        } else if(qName.equals("book")) {
            System.out.println("--------------------------------");
            System.out.println("kind: " + atts.getValue("kind"));
        } else {
            System.out.print(qName + ": ");
        }        
    }
 
    // 끝 태그를 만났을 때 발생하는 이벤트를 처리하는 메소드
    public void endElement(String uri, String localName, String qName) throws SAXException {
        System.out.println();
    }
 
    // 문자 데이터를 만났을 때 발생하는 이벤트를 처리하는 메소드
    public void characters(char[] ch, int start, int length) throws SAXException {
        String content = new String(ch, start, length);
        System.out.print(content);
    }
 
    public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {}
    public void processingInstruction(String target, String data) throws SAXException {}
    public void skippedEntity(String name) throws SAXException {}
 
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 
 
import javax.xml.parsers.*;
import org.xml.sax.*;
 
public class SettingContentHandler {
    public static void main(String args[]) throws Exception {    
        // 파서 생성
        SAXParserFactory factory =  SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        XMLReader reader = parser.getXMLReader();    // XML 리더 객체
 
        // DTDHandler 객체 생성
        ContentHandler contentHandler = new MyContentHandler();
 
        // contentHandler 객체 등록
        reader.setContentHandler(contentHandler);
 
        // 파싱 지시
        reader.parse("bml.xml");
    }    
}

 

 

 

반응형