반응형
생성자 자동 만들기
제네릭을 썻는데 오류가 난다면 properties에서 java Compiler Level을 1.5이상으로 변경해줘야한다.
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 | <?xml version="1.0" encoding="euc-kr"?> <!-- 엘리먼트 선언 --> <!ELEMENT booklist (book*)> <!ELEMENT book (title, author, publisher, price, image?, desc?)> <!ELEMENT title (#PCDATA)> <!ELEMENT author (#PCDATA)> <!ELEMENT publisher (#PCDATA)> <!ELEMENT price (#PCDATA)> <!ELEMENT image EMPTY> <!ELEMENT desc (#PCDATA)> <!-- 속성 선언 --> <!ATTLIST book kind CDATA #REQUIRED> <!ATTLIST image ename ENTITY #IMPLIED src CDATA #IMPLIED> <!-- 노테이션 선언 --> <!NOTATION nGIF PUBLIC "image/gif" "C:/Program Files/Internet Explorer/iexplore.exe"> <!NOTATION nJPEG PUBLIC "image/jpeg" "C:/Program Files/Internet Explorer/iexplore.exe"> <!-- 외부 언파스드 엔티티 선언 (NDATA가 붙으면 언파스드 엔티티이다.) 언파스드는 직접 처리를 해줘야한다.--> <!ENTITY eB1Image SYSTEM "b1Image.jpg" NDATA nJPEG> <!ENTITY eB2Image SYSTEM "b2Image.gif" NDATA nGIF> <!ENTITY eB3Image SYSTEM "b3Image.gif" NDATA nGIF> <!-- 외부 파스드 엔티티 선언 --> <!ENTITY eB1Desc SYSTEM "b1Desc.txt"> <!ENTITY eB2Desc SYSTEM "b2Desc.txt"> <!ENTITY eB3Desc SYSTEM "b3Desc.txt"> |
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 | // VO = Value Object 값을 저장하는 용도 // 노테이션을 처리한다. public class NotationDecl { private String name; private String publicId; private String systemId; public NotationDecl(String name, String publicId, String systemId) { this.name = name; this.publicId = publicId; this.systemId = systemId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPublicId() { return publicId; } public void setPublicId(String publicId) { this.publicId = publicId; } public String getSystemId() { return systemId; } public void setSystemId(String systemId) { this.systemId = systemId; } } |
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 | //언파스드의 내용을 저장 public class UnParsedEntityDecl { private String name; private String publicId; private String systemId; private String notationName; public UnParsedEntityDecl(String name, String publicId, String systemId, String notationName) { this.name = name; this.publicId = publicId; this.systemId = systemId; this.notationName = notationName; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPublicId() { return publicId; } public void setPublicId(String publicId) { this.publicId = publicId; } public String getSystemId() { return systemId; } public void setSystemId(String systemId) { this.systemId = systemId; } public String getNotationName() { return notationName; } public void setNotationName(String notationName) { this.notationName = notationName; } } |
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 | import java.net.URL; import java.net.URLDecoder; import java.util.*; import org.xml.sax.DTDHandler; import org.xml.sax.SAXException; public class MyDTDHandler implements DTDHandler { // Hashtable(과거에 호환성때문에 남아있음) --> HashMap private HashMap<String, NotationDecl> notationDeclMap; // 제네릭 // Vector --> ArrayList 사용 권장 private ArrayList<UnParsedEntityDecl> unParsedEntityList; public MyDTDHandler() { notationDeclMap = new HashMap<String, NotationDecl>(); unParsedEntityList = new ArrayList<UnParsedEntityDecl>(); } public void notationDecl(String name, String publicId, String systemId) throws SAXException { NotationDecl notationDecl = new NotationDecl(name, publicId, systemId); notationDeclMap.put(name, notationDecl); } public void unparsedEntityDecl(String name, String publicId, String systemId, String notationName) throws SAXException { UnParsedEntityDecl unParsedEntityDecl = new UnParsedEntityDecl(name, publicId, systemId, notationName); unParsedEntityList.add(unParsedEntityDecl); } public void showImage() throws Exception{ for(UnParsedEntityDecl unParsedEntityDecl: unParsedEntityList){ URL urlImageFile = new URL(unParsedEntityDecl.getSystemId()); String imageFile = URLDecoder.decode(urlImageFile.getFile(), "euc-kr"); imageFile = imageFile.replace("/C:", "C:"); NotationDecl notationDecl = notationDeclMap.get(unParsedEntityDecl.getNotationName()); URL urlHelperProgram = new URL(notationDecl.getSystemId()); String helperProgram = URLDecoder.decode(urlHelperProgram.getFile(), "euc-kr"); helperProgram = helperProgram.replace("/C:", "C:"); String command = helperProgram+" "+imageFile; System.out.println(command); Runtime.getRuntime().exec(command); } } } |
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 | import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl; public class SettingDTDHandler { public static void main(String[] args) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); MyDTDHandler myDTDHandler = new MyDTDHandler(); reader.setDTDHandler(myDTDHandler); reader.parse("bml.xml"); myDTDHandler.showImage(); } } |
결과값 :
디자인패턴 - Decorator 패턴
FileReader - read메소드로 한 바이트씩만 읽을 수 있다.
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 | import org.xml.sax.*; import java.net.*; import java.io.*; public class MyEntityResolver implements EntityResolver { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { URL urlFileName = new URL(systemId); String fileName = URLDecoder.decode(urlFileName.getFile(), "euc-kr"); fileName = fileName.replaceAll("/C:", "C:"); System.out.println("\n\n\n**************************************************"); System.out.println(fileName); System.out.println("**************************************************"); //디자인패턴 - Decorator 패턴 //FileReader - read메소드로 한 바이트씩만 읽을 수 있다. File file = new File(fileName); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String rowData = null; while((rowData = br.readLine())!=null) { System.out.println(rowData); } return null; } } |
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 SettingEntityResolver { public static void main(String args[]) throws Exception { // 파서 생성 SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); // EntityResolver 객체 생성 EntityResolver entityResolver = new MyEntityResolver(); // EntityResolver 객체 등록 reader.setEntityResolver(entityResolver); // 파싱 지시 reader.parse("bml.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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | import org.xml.sax.*; import org.xml.sax.helpers.*; import java.util.*; public class FindBookEventHandler extends DefaultHandler { ///Field private boolean isBook, isTitle, isAuthor, isPublisher, isPrice; private String condition, keyWord; private Hashtable hash; private Attributes attributes; ///Constructor public FindBookEventHandler(String condition, String keyWord) { //검색 엘리먼트 this.condition = condition; //검색 문자열 this.keyWord = keyWord; //검색 내용을 저장할 Hashtable 객체 this.hash = new Hashtable(); } ///Method public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if(qName.equals("book")) { isBook = true; String kind = attributes.getValue("kind"); hash.put("kind", kind); } else if(qName.equals("title")) { isTitle = true; } else if(qName.equals("author")) { isAuthor = true; } else if(qName.equals("publisher")) { isPublisher = true; } else if(qName.equals("price")) { isPrice = true; } } public void characters(char[] ch, int start, int length) throws SAXException { String str = new String(ch,start,length).trim(); if(isTitle) { hash.put("title", str); isTitle = false; } else if(isAuthor) { hash.put("author", str); isAuthor = false; } else if(isPublisher) { hash.put("publisher", str); isPublisher = false; } else if(isPrice) { hash.put("price", str); isPrice = false; } } public void endElement(String uri, String localName, String qName) throws SAXException { if(qName.equals("book")) { if(condition.equals("kind")) { String kind = (String) hash.get("kind"); if(kind.indexOf(keyWord)!=-1) displayBookInfo(); } else if(condition.equals("title")) { String title = (String) hash.get("title"); if(title.indexOf(keyWord)!=-1) displayBookInfo(); } else if(condition.equals("author")) { String author = (String) hash.get("author"); if(author.indexOf(keyWord)!=-1) displayBookInfo(); } else if(condition.equals("publisher")) { String publisher = (String) hash.get("publisher"); if(publisher.indexOf(keyWord)!=-1) displayBookInfo(); } hash.clear(); isBook = false; } } public void displayBookInfo() { System.out.println("title: " + (String) hash.get("title")); System.out.println("author: " + (String) hash.get("author")); System.out.println("publisher: " + (String) hash.get("publisher")); System.out.println("price: " + (String) hash.get("price")); System.out.println("----------------------"); } public void warning(SAXParseException exception) throws SAXException { throw new SAXException("warning 이벤트 처리"); } public void error(SAXParseException exception) throws SAXException { System.out.println("DTD 또는 XML Schema 문서 구조에 위배됩니다."); System.out.println("유효하지 않는 문서 입니다."); throw new SAXException("error 이벤트 처리"); } public void fatalError(SAXParseException exception) throws SAXException { System.out.println("XML 권고안의 내용을 지키지 않았습니다."); System.out.println("잘 짜여진 XML 문서가 아닙니다."); throw new SAXException("fatalError 이벤트 처리"); } } |
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 | import javax.xml.parsers.*; public class FindBook { ///Field ///Constructor ///Method public static void main(String args[]) { try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); System.out.println("########################################"); System.out.println("책 제목으로 검색"); System.out.println("########################################"); FindBookEventHandler handler = new FindBookEventHandler("title", "XML"); parser.parse("bml.xml", handler); System.out.println("########################################"); System.out.println("책 종류으로 검색"); System.out.println("########################################"); handler = new FindBookEventHandler("kind", "소설"); parser.parse("bml.xml", handler); } catch(Exception e) { e.printStackTrace(); } } } |
결과값
########################################
책 제목으로 검색
########################################
title: XML 웹 서비스
author: 신용권
publisher: 프리렉
price: 29000
----------------------
########################################
책 종류으로 검색
########################################
title: 천국에서 만난 다섯사람
author: 미치앨봄
publisher: 세종서적
price: 9000
----------------------
Pull 파서 사용
http://www.kxml.org/ 가서 kxml2.jar파일을 다운받아야 사용이 가능하다.
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 | import java.io.FileReader; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; public class PullParserExample { public static void main(String[] args) { boolean inTitle = false; String title=""; try{ XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser parser = factory.newPullParser(); parser.setInput(new FileReader("bml2.xml")); int eventType = parser.getEventType(); while(eventType != XmlPullParser.END_DOCUMENT){ switch(eventType){ case XmlPullParser.START_DOCUMENT: case XmlPullParser.END_DOCUMENT: case XmlPullParser.END_TAG: break; case XmlPullParser.START_TAG: if(parser.getName().equals("title")){ inTitle = true; } break; case XmlPullParser.TEXT: if(inTitle){ title = parser.getText(); System.out.println("title=>" + title); inTitle = false; } break; } eventType = parser.next(); } }catch(Exception e){ e.printStackTrace(); } } } |
출력값 :
title=>XML 웹 서비스
title=>금붕어메세지
title=>Java And XML
반응형
'(Before)BitSchool' 카테고리의 다른 글
2014/06/12 JavaScript - 기본함수, 사용자 함수, 이벤트 (0) | 2014.06.12 |
---|---|
2014/06/11 JavaScript (0) | 2014.06.11 |
2014/06/10 XML - xml파서, DOM 수정, 추가, 삭제, SAX 파서 (0) | 2014.06.10 |
2014/06/03 XML (0) | 2014.06.03 |
2014/05/31 JSP - JDBC, connectionPool (0) | 2014.05.31 |