DOM l DOM Level 3 API l DOM

  • Slides: 48
Download presentation

DOM 파서 l DOM Level 3 API에 기반 l 무료 이용 가능 DOM 파서

DOM 파서 l DOM Level 3 API에 기반 l 무료 이용 가능 DOM 파서 종류 정보 JAXP(Java API for XML Processing) 오라클에서 제공 http: //docs. oracle. com/javase/tutorial /jaxp/intro/index. html Apache Xalan 아파치 소프트웨어재단에서 제공 http: /xalan. apache. org/ Xerces(Xerces Java Parser) 아파치 소프트웨어재단에서 제공 http: //xerces. apache. org/ MSXML MS에서 제공 http: //www. microsoft. com/ 8

예제: DOM 파싱 l 관련된 패키지 import org. w 3 c. dom. Document; import

예제: DOM 파싱 l 관련된 패키지 import org. w 3 c. dom. Document; import org. w 3 c. dom. Element; import org. w 3 c. dom. Node. List; import org. w 3 c. dom. Node; import javax. xml. parsers. Document. Builder. Factory; import javax. xml. parsers. Document. Builder; import javax. xml. parsers. Parser. Configuration. Exception; import org. xml. sax. SAXException; import java. io. IOException; import java. io. File; 11

예제: DOM 파싱 l 파서를 생성하고 DOM 트리 구성 // 참조 변수 선언 Document

예제: DOM 파싱 l 파서를 생성하고 DOM 트리 구성 // 참조 변수 선언 Document doc = null; String xml. Document = "policies. xml"; <? xml version="1. 0"? > <policies> <company-domain>http: //www. webhomecover. com</company-domain> <contents-image>contents. gif</contents-image> <buildings-image>buildings. gif</buildings-image> <policy type="contents"> <policy-holder>A. Liu</policy-holder> <claims> <claim> <year>2002</year><details>Stolen TV</details> </claims> </policy> <policy type="contents"> <policy-holder>B. Singh</policy-holder> </policy> … import org. w 3 c. dom. Document; import org. w 3 c. dom. Element; import org. w 3 c. dom. Node. List; import org. w 3 c. dom. Node; import javax. xml. parsers. Document. Builder. Factory; import javax. xml. parsers. Document. Builder; import javax. xml. parsers. Parser. Configuration. Exception; import org. xml. sax. SAXException; // 입력 문서 파싱 import java. io. IOException; try import java. io. File; { Document. Builder. Factory dbf = Document. Builder. Factory. new. Instance(); Document. Builder. Factory 객체 생성 Document. Builder db = dbf. new. Document. Builder(); doc = db. parse(new File(xml. Document)); Document. Builder(파서)객체 생성 } XML 문서에 대한 DOM 트리 생성 // 예외 처리기 catch(…) { 12

예제: DOM 파싱 l DOM 트리의 루트 요소 이름 추출 <? xml version="1. 0"?

예제: DOM 파싱 l DOM 트리의 루트 요소 이름 추출 <? xml version="1. 0"? > <policies> <company-domain>http: //www. webhomecover. com</company-domain> <contents-image>contents. gif</contents-image> <buildings-image>buildings. gif</buildings-image> <policy type="contents"> <policy-holder>A. Liu</policy-holder> <claims> <claim> <year>2002</year><details>Stolen TV</details> </claims> </policy> <policy type="contents"> <policy-holder>B. Singh</policy-holder> </policy> … Element root = doc. get. Document. Element(); String root. Tag. Name = root. get. Tag. Name(); System. out. println("The root element tag is <" + root. Tag. Name + ">"); l get. Elements. By. Tag. Name()을 이용하여 노드 리스트 추출 Node. List l = root. get. Elements. By. Tag. Name("policy"); int n = l. get. Length(); System. out. println("There are " + n + " policies"); 13

예제: DOM 파싱 l 첫번째 자식 노드 및 노드 값 추출 <? xml version="1.

예제: DOM 파싱 l 첫번째 자식 노드 및 노드 값 추출 <? xml version="1. 0"? > <policies> <company-domain>http: //www. webhomecover. com</company-domain> <contents-image>contents. gif</contents-image> <buildings-image>buildings. gif</buildings-image> <policy type="contents"> <policy-holder>A. Liu</policy-holder> <claims> <claim> <year>2002</year><details>Stolen TV</details> </claims> </policy> <policy type="contents"> <policy-holder>B. Singh</policy-holder> </policy> … // the company-domain 노드 추출 Node. List domain. Nodes = root. get. Elements. By. Tag. Name("company-domain"); Node domain. Node = domain. Nodes. item(0); // 노드 값 추출 System. out. println("Domain: " + domain. Node. get. First. Child(). get. Node. Value()); 14

예제: DOM 파싱 l 자식 노드 리스트 <? xml version="1. 0"? > <policies> <company-domain>http:

예제: DOM 파싱 l 자식 노드 리스트 <? xml version="1. 0"? > <policies> <company-domain>http: //www. webhomecover. com</company-domain> <contents-image>contents. gif</contents-image> <buildings-image>buildings. gif</buildings-image> <policy type="contents"> <policy-holder>A. Liu</policy-holder> <claims> <claim> <year>2002</year><details>Stolen TV</details> </claims> </policy> <policy type="contents"> <policy-holder>B. Singh</policy-holder> </policy> … // 루트의 자식 노드 리스트 System. out. println("The child elements for the root are: "); Node. List nodes = root. get. Child. Nodes(); for(int i=0; i < nodes. get. Length(); i++) { Node node = nodes. item(i); String node. Name = node. get. Node. Name(); // 요소간의 공백이나 빈줄은 '#text' 노드로 표현: 이들을 무시함 if(!node. Name. equals("#text")) { System. out. println(node. Name); } } 15

<? xml version="1. 0"? > <policies> <company-domain>http: //www. webhomecover. com</company-domain> <contents-image>contents. gif</contents-image> <buildings-image>buildings. gif</buildings-image>

<? xml version="1. 0"? > <policies> <company-domain>http: //www. webhomecover. com</company-domain> <contents-image>contents. gif</contents-image> <buildings-image>buildings. gif</buildings-image> <policy type="contents"> <policy-holder>A. Liu</policy-holder> <claims> <claim> <year>2002</year><details>Stolen TV</details> </claims> </policy> <policy type="contents"> <policy-holder>B. Singh</policy-holder> </policy> … Program Output 16

DOM 모델 (3) l DOM Core 확장 인터페이스 종류 내용 CDATASection XML 문서에서 CDATA

DOM 모델 (3) l DOM Core 확장 인터페이스 종류 내용 CDATASection XML 문서에서 CDATA Section에 해당 Document. Type 문서의 타입 정의에 해당하는 객체 Notation DTD의 Notation에 해당하는 객체 Entity. Reference XML 문서에서 Entity에 대한 참조에 해당하는 객체 Entity XML 문서에서 Entity에 해당 Processing. Instruction XML 문서의 processing instruction 부분에 해당 19

Node 인터페이스 (2) l Node 타입을 표현하는 정적 멤버 필드를 가짐 노드 타입 상수값

Node 인터페이스 (2) l Node 타입을 표현하는 정적 멤버 필드를 가짐 노드 타입 상수값 ELEMENT_NODE 1 PROCESSING_INSTRUCTION_NODE 7 ATTRIBUTE_NODE 2 COMMENT_NODE 8 TEST_NODE 3 DOCUMENT_NODE 9 CDATA_SECTION_NODE 4 DOCUMENT_TYPE_NODE 10 ENTITY_REFERENCE_NOD E 5 DOCUMENT_FRAGMENT_NODE 11 ENTITY_NODE 6 NOTATION_NODE 12 21

예제 <HTML> <HEAD><TITLE> DOM example </TITLE> <SCRIPT language="javascript"> // MSXML 파서를 이용하여 Document 객체

예제 <HTML> <HEAD><TITLE> DOM example </TITLE> <SCRIPT language="javascript"> // MSXML 파서를 이용하여 Document 객체 생성 var obj. Doc; obj. Doc = new Active. XObject("MSXML. DOMDocument"); <students> students. xml <student> <name> 박미영 </name> <age> 25 </age> </student> <name> 고소영 </name> <age> 24 </age> </students> // XML 문서를 읽어들여서 파싱 obj. Doc. async=false; obj. Doc. load("students. xml"); // 루트 노드 정보를 추출하고 메시지 창에 출력한다. var obj. Root. Node; obj. Root. Node = obj. Doc. document. Element; alert(" node. Name : " + obj. Root. Node. node. Name + "n node. Value : " + obj. Root. Node. node. Value + "n node. Type : " + obj. Root. Node. node. Type ); </SCRIPT> </HEAD> <BODY> DOM을 활용한 XML 문서 조작 </BODY> </HTML> 23

dom. xml 예제 24

dom. xml 예제 24

Node 인터페이스 (4) l 노드 정보를 제공하는 메쏘드 메소드 내용 String get. Node. Name()

Node 인터페이스 (4) l 노드 정보를 제공하는 메쏘드 메소드 내용 String get. Node. Name() 노드 이름을 반환 String get. Node. Value() 노드 값을 반환 void set. Node. Value(String node. Value) 노드 값을 설정 short get. Node. Type() 노드 타입을 반환 Named. Node. Map get. Attributes() 속성을 반환 Document get. Owner. Document() 현재 노드가 속한 문서를 반환 25

dom. xml 예제 28

dom. xml 예제 28

Document 인터페이스 l XML 문서 표현 l DOM 구조를 순회하기 위한 메쏘드 제공 메쏘드

Document 인터페이스 l XML 문서 표현 l DOM 구조를 순회하기 위한 메쏘드 제공 메쏘드 설명 get. Doctype() 문서에 포함된 DOCTYPE을 반환 get. Document. Element() 루트 요소 반환 get. Element. By. Id(String ID) ID를 갖는 요소 반환 get. Elements. By. Tag. Name(String tag. Name) tag. Name을 갖는 모든 요소의 Node. List 반환 29

Document 인터페이스 메소드 l DOM 조작 메쏘 드 제공 내용 Element create. Element(String tag.

Document 인터페이스 메소드 l DOM 조작 메쏘 드 제공 내용 Element create. Element(String tag. Name) 지정된 이름의 요소를 만들 때 사용하는 메소드로, tag. Name에 지정된 이름의 요소를 생성 Element create. Element. Ns(String namespace. URI, String qulified. Name) 주어진 이름과 네임스페이스를 이용해서 요소를 생성 Document. Fragment create. Document. Fragment() 비어있는 Document. Fragment 객체를 생성 Text create. Text. Node(String data) data에 텍스트가 있는 text 노드를 생성 Comment create. Comment(String data) data에 텍스트가 있는 Comment 노드를 생성 CDATASection create. CDATASection(String data) data에 있는 텍스트가 CDATASection 노드를 생성 Processing. Instruction create. Processing. Instruction(String target, String data) 지정된 target과 data를 가진 Processing. Instruction 노드를 생성. Processing. Instruction이 가리키는 애플리케이션을 지정하는 문자열이 오고, data는 target을 제외한 나머지 부분의 문자열이 온다. Attr create. Attribute(String name) 지정된 name 속성을 생성. 만들어진 노드는 노드 인터페이스의 node. Name 속성에 접근을 할수 있다. Attr create. Attribute. NS(String namespace. URI, String qulified. Name) 주어진 이름과 네임스페이스를 이용해서 속성을 생성 Entity. Reference create. Entity. Reference(String name) Node import. Node(Node import. Node, boolean deep) 지정된 name의 개체 참조를 생성 필요한 곳으로 노드를 복사할 수 있도록 함 다른 문서에서 이 문서로 import. Node 노드를 가져온다. 원래의 노드는 이전의 문서에서 제거되지 않고 복사된다. deep속성은 deep 또는 shallow clone을 지정 한다. 30

예제 student. Attr. xml 38

예제 student. Attr. xml 38

예제: Java DOM API // parse an XML document Document document = builder. parse(xml.

예제: Java DOM API // parse an XML document Document document = builder. parse(xml. File); // retrieving the root element Name Element root. Element = docment. get. Docment. Element(); String root. Element. Name = root. Element. get. Tag. Name(); // retrieving root element attributes If (root. Element. has. Attributes() { Named. Node. Map attributes = root. Element. get. Attributes(); } // Retrieving Attribute Values for (int i=0; i< attributes. get. Length(); i++) { Attr attribute = (Attr)attributes. item(i)); System. out. println(“Attribute: ” + attribute. get. Name() + “ with value “ + attribute. get. Value()); // retrieving Nodes in the root element If (root. Element. has. Child. Nodes()) { Node. List node. List = root. Element. get. Child. Nodes(); } // retrieving Nodes in a node. List // the node list includes whitespace text nodes for (int i=0; I < node. List. get. Length(); i++) { Node node = node. List. item(i); if (node. get. Node. Type() == Node. ELEMENT_NODE) { // if a node is of type Element element = (Element) node; if (node. get. Node. Type() == Node. TEXT_NODE) { // if a node is of type Element} String text. Value = node. get. Node. Value(); …. . 40

예제: Java DOM API. java 41

예제: Java DOM API. java 41

예제: Java DOM API package com. apress. dom; import javax. xml. parsers. Document. Builder.

예제: Java DOM API package com. apress. dom; import javax. xml. parsers. Document. Builder. Factory; import javax. xml. parsers. Parser. Configuration. Exception; import org. w 3 c. dom. *; import org. xml. sax. SAXException; import java. io. *; public class DOMParser { public static void main(String argv[]) { try { // Create a Document. Builder. Factory factory = Document. Builder. Factory. new. Instance(); File xml. File = new File("catalog. xml"); // Create a Document. Builder builder = factory. new. Document. Builder(); // Parse an XML document Document document = builder. parse(xml. File); // Retrieve Root Element root. Element = document. get. Document. Element(); System. out. println("Root Element is: " + root. Element. get. Tag. Name()); visit. Node(null, root. Element); } catch (SAXException e) { System. out. println(e. get. Message()); } catch (Parser. Configuration. Exception e) { System. out. println(e. get. Message()); } catch (IOException e) { System. out. println(e. get. Message()); } 42 }

public static void visit. Node(Element previous. Node, Element visit. Node) { if (previous. Node

public static void visit. Node(Element previous. Node, Element visit. Node) { if (previous. Node != null) { System. out. println("Element " + previous. Node. get. Tag. Name() + " has element: "); } System. out. println("Element Name: " + visit. Node. get. Tag. Name()); if (visit. Node. has. Attributes()) { System. out. println("Element " + visit. Node. get. Tag. Name() + " has attributes: "); Named. Node. Map attributes = visit. Node. get. Attributes(); 예제: Java DOM API for (int j = 0; j < attributes. get. Length(); j++) { Attr attribute = (Attr) (attributes. item(j)); System. out. println("Attribute: " + attribute. get. Name() + " with value " + attribute. get. Value()); } } // Obtain a Node. List of nodes in an Element node. Node. List node. List = visit. Node. get. Child. Nodes(); for (int i = 0; i < node. List. get. Length(); i++) { Node node = node. List. item(i); // Retrieve Element Nodes if (node. get. Node. Type() == Node. ELEMENT_NODE) { Element element = (Element) node; visit. Node(visit. Node, element); } else if (node. get. Node. Type() == Node. TEXT_NODE) { String str = node. get. Node. Value(). trim(); if (str. length() > 0) { System. out. println("Element Text: " + str); } } 43 }

예제: Java DOM API l XML 문서 입력/출력 import java. io. *; import javax.

예제: Java DOM API l XML 문서 입력/출력 import java. io. *; import javax. xml. parsers. *; import org. w 3 c. dom. *; import org. apache. crimson. tree. *; class DOMIO { public static void main(String[] args) throws Exception { if (args. length != 2) { System. out. println("usage : >java DOMIO <input-file name> <output-file name>"); System. exit(1); } String infilename= args[0]; String outfilename= args[1]; //DOM를 준비한다 Document. Builder. Factory Doc. BF = Document. Builder. Factory. new. Instance(); Document. Builder Doc. B = Doc. BF. new. Document. Builder(); //문서 읽어들이기 Document Doc= Doc. B. parse(new File. Input. Stream(infilename)); //문서 써넣기 Xml. Document XDoc = (Xml. Document) Doc; Buffered. Writer Buf. W = new Buffered. Writer(new File. Writer(outfilename)); XDoc. write(Buf. W, "euc-kr"); } } 44

예제: Java DOM API l 데이터 추가 import java. io. *; import javax. xml.

예제: Java DOM API l 데이터 추가 import java. io. *; import javax. xml. parsers. *; import org. w 3 c. dom. *; import org. apache. crimson. tree. *; class Create. Data { public static void main(String args[]) throws Exception { // … 문서 읽어들이기 Document doc = db. parse(new File. Input. Stream(args[0])); //문서의 출발점을 얻는다 Element root = doc. get. Document. Element(); //노드의 자(child)를 찾아간다 public static void add. Data(Node n) { //노드의 자(child)를 찾아간다 add. Data(root); for(Node ch = n. get. First. Child(); ch != null; ch = ch. get. Next. Sibling()) { //문서 써넣기 Xml. Document xdoc = (Xml. Document) doc; Buffered. Writer bw = new Buffered. Writer(new File. Writer(args[1])); xdoc. write(bw, "EUC-KR"); //요소를 처리한다 if(ch. get. Node. Type() == Node. ELEMENT_NODE) { if(ch. get. Node. Name(). equals("student")) { Document doc = ch. get. Owner. Document(); Element comp = doc. create. Element("school"); Text txt = doc. create. Text. Node("한국대학교"); ch. append. Child(comp); comp. append. Child(txt); } add. Data(ch); } } } src: students. xml <? xml version = “ 1. 0”? > <students> <student> <name> Gildong</name> <age>25</age> </student> <name> Chunhyang</name> <age>16</age> </students> Output? 45

예제: Java DOM API l 데이터 삭제 //노드의 자(child)를 찾아간다 public static void del.

예제: Java DOM API l 데이터 삭제 //노드의 자(child)를 찾아간다 public static void del. Data(Node n) { for(Node ch = n. get. First. Child(); ch != null; ch = ch. get. Next. Sibling()) { //요소를 처리한다 if(ch. get. Node. Type() == Node. ELEMENT_NODE) { if(ch. get. Node. Name(). equals("age")) { Node pr = ch. get. Parent. Node(); pr. remove. Child(ch); } del. Data(ch); } } import org. w 3 c. dom. *; import org. apache. crimson. tree. *; class Delete. Data { public static void main(String args[]) throws Exception { if (args. length != 2) { System. out. println("usage : >java Delete. Data <input-file name> <output-file name>"); System. exit(1); } //DOM를 준비한다 Document. Builder. Factory dbf = Document. Builder. Factory. new. Instance(); Document. Builder db = dbf. new. Document. Builder(); //문서 읽어들이기 Document doc = db. parse(new File. Input. Stream(args[0])); //문서의 출발점을 얻는다 Element root = doc. get. Document. Element(); //노드의 자(child)를 찾아간다 del. Data(root); //문서 써넣기 src: students. xml Xml. Document xdoc = (Xml. Document) doc; <? xml version = “ 1. 0”? > Buffered. Writer bw = new Buffered. Writer(new File. Writer(args[1])); <students> xdoc. write(bw, "EUC-KR"); Output? <student> <name> Gildong</name> } <age>25</age> </student> <name> Chunhyang</name> <age>16</age> </students> 46

예제: Java DOM API l 데이터 추출 //요소를 추출한다 Node. List lst = doc.

예제: Java DOM API l 데이터 추출 //요소를 추출한다 Node. List lst = doc. get. Elements. By. Tag. Name("name"); for(int i=0; i<lst. get. Length(); i++){ Node n = lst. item(i); for(Node ch = n. get. First. Child(); ch != null; ch = ch. get. Next. Sibling()) { Element elm = doc 2. create. Element("name"); Text txt = doc 2. create. Text. Node(ch. get. Node. Value()); elm. append. Child(txt); root. append. Child(elm); } } //문서 써넣기 Xml. Document xdoc = (Xml. Document) doc 2; Buffered. Writer bw = new Buffered. Writer(new. File. Writer(args[1])); xdoc. write(bw, "EUC-KR"); } } import javax. xml. parsers. *; import org. w 3 c. dom. *; import org. apache. crimson. tree. *; class select. Data { public static void main(String args[]) throws Exception { if (args. length != 2) { System. out. println("usage : >java select. Data <input-file name> <output-file name>"); System. exit(1); } //DOM를 준비한다 Document. Builder. Factory dbf = Document. Builder. Factory. new. Instance(); Document. Builder db = dbf. new. Document. Builder(); //문서 읽어들이기 Document doc = db. parse(new File. Input. Stream(args[0])); //문서를 새로 작성한다 Document doc 2 = db. new. Document(); //루트 요소를 추가한다 Element root = doc 2. create. Element("students"); doc 2. append. Child(root); <? xml version = “ 1. 0”? > src: students. xml <students> <student> <name> Gildong</name> <age>25</age> </student> <name> Chunhyang</name> <age>16</age> </students> Output? 47

Report #7(11/16, due 11/30) l 9장 심화문제: #1 ~#3 48

Report #7(11/16, due 11/30) l 9장 심화문제: #1 ~#3 48