[JAVA+국비교육] XML파일 읽어오기, 정규화 표현식
by 무작정 개발반응형
2022.01.17(20일 차)
오늘의 수업 내용
XML 파일 읽어오기
javapackage com.day19; import java.io.InputStream; import java.net.URL; 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; public class Test1 { public static void main(String[] args) { try { //Dom Document 객체를 생성하기 위해 팩토리 생성. DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = f.newDocumentBuilder(); //Dom parser로 부터 입력받은 파일을 파싱함. Document xmlDoc = null; String url = "book.xml"; //데모에있는 book.xml을 읽어온다. if(url.indexOf("http://")!=-1) { //없지않으면 ,있으면 이라는뜻 //내pc 외부에있으면 읽어오고 URL u = new URL(url); InputStream is = u.openStream(); xmlDoc = parser.parse(is); }else {//내 pc 내부에 있으면 읽어와라. xmlDoc = parser.parse(url); //parser를 가지고 파싱해서 url을 만들어라. } //Element : xml문서의 요소를 표현하기 위해 사용한다. Element root = xmlDoc.getDocumentElement(); //읽어오기 System.out.println(root.getTagName()); //첫번째 book //Node : 각 요소를 읽기위해 사용한다. Node book1 = root.getElementsByTagName("book").item(0); System.out.println(((Element)book1).getAttribute("kind")); Node title = book1.getFirstChild(); //System.out.println(title); Node title1 = title.getNextSibling(); System.out.println(title1.getNodeName()); Node title1_1 = title1.getFirstChild(); System.out.println(title1_1.getNodeValue()); } catch (Exception e) { } } }
java<!DOCTYPE html> <html> <head> <meta charset="EUC-KR"> <title>Book XML 파싱</title> <script type="text/javascript"> var xmlDoc = new ActiveXObject("Msxml2.DOMDocument"); xmlDoc.load("book.xml"); function printNodeItem(){ //var root = xmlDoc.getElementsByTagName("booklist")[0]; 아래와 같은코딩 var root = xmlDoc.documentElement; var books = root.getElementsByTagName("book"); var out = ""; for(var i=0;i<books.length;i++){ //var book = books[i]; 처럼 변수에 넣어 짧게 써줄수도있다. //books의 0번째 1번째 out += "\n분류: " + books[i].getAttribute("kind") + ", 제목: " + books[i].getElementsByTagName("title")[0] .firstChild.nodeValue + ", 저자: " + books[i].getElementsByTagName("author")[0] .firstChild.nodeValue + ", 가격: " + books[i].getElementsByTagName("price")[0] .firstChild.nodeValue; } alert(out); } </script> </head> <body> <input type="button" value="노드출력" onclick="printNodeItem();"/> </body> </html>
javapackage com.day19; import java.io.InputStream; import java.net.URL; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Test2 { public static void main(String[] args) { try { //Dom Document 객체를 생성하기위해 팩토리 생성 DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = f.newDocumentBuilder(); //Dom 파서로부터 입력받은 파일을 파싱함 Document xmlDoc = null; String url = "book.xml"; if(url.indexOf("http://")!=-1) { URL u = new URL(url); InputStream is = u.openStream(); xmlDoc = parser.parse(is); }else { xmlDoc = parser.parse(url); } Element root = xmlDoc.getDocumentElement(); NodeList books = root.getElementsByTagName("book"); String out = ""; String str; for(int i=0;i<books.getLength();i++) { Node book = books.item(i); str = book.getNodeName(); out += "노드명: " + str; NamedNodeMap bookMap = book.getAttributes(); str = bookMap.getNamedItem("kind").getNodeValue(); out += ", kind: " + str; NodeList elementList = book.getChildNodes(); for(int j=0;j<elementList.getLength();j++) { Node e = elementList.item(j); str = ""; if(e.getNodeType()==Node.ELEMENT_NODE) { str = ", " + e.getNodeName(); out += str + ":"; out += e.getChildNodes().item(0).getNodeValue(); } } out += "\n"; } System.out.println(out); } catch (Exception e) { // TODO: handle exception } } }
javapackage com.day19; import java.io.File; import java.net.Socket; import java.util.Scanner; public class FileClientTest { public static void main(String[] args) { int port = 777; String host = "local host"; Socket sc = null; Scanner scn = new Scanner(System.in); String filePath; try { System.out.print("전송할 파일경로 및 파일명 : "); // d:\\doc\\a.txt filePath = scn.next(); //경로를 찾아갔는데 파일이 없을수 있으니 검증하기 File f = new File(filePath); } catch (Exception e) { // TODO: handle exception } } }
javapackage com.day19; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.net.ServerSocket; import java.net.Socket; public class FileServerTest { class WorkThread extends Thread { private Socket sc = null; public WorkThread(Socket sc) { this.sc = sc; } @Override public void run() { try { //직렬화된 데이터가 넘어옴 ObjectInputStream ois = new ObjectInputStream(sc.getInputStream()); System.out.println(sc.getInetAddress().getAddress() + "접속...."); FileOutputStream fos = null; Object ob = null; while((ob = ois.readObject()) != null) { if(ob instanceof FileInfo) { FileInfo info = (FileInfo)ob; if(info.getCode() == 100) { //파일전송시작 String str = new String(info.getData()); // getData를 받아와서 문자화 한다 fos = new FileOutputStream(str); // 파일 생성 System.out.println(str + "파일 전송 시작!!"); } else if(info.getCode() == 110) {//파일전송중 if(fos == null) break; fos.write(info.getData(), 0, info.getSize()); System.out.println(info.getSize() + "bytes 받는중..."); } else if(info.getCode() == 200) { // 파일전송끝 if(fos == null) break; String str = new String(info.getData()); fos.close(); System.out.println(str + "파일전송 끝"); break; //파일 전송이 다끝났으니 while문 나오기 위해 break사용 } } } } catch (Exception e) { System.out.println(e.toString()); } } } public void serverStart() { try { ServerSocket ss = new ServerSocket(7777); System.out.println("클라이언트 접속 대기중..."); Socket sc = ss.accept(); WorkThread wt = new WorkThread(sc); wt.start(); // 서버 끝 } catch (Exception e) { System.out.println(e.toString()); } } public static void main(String[] args) { new FileServerTest().serverStart(); } }
반응형
블로그의 정보
무작정 개발
무작정 개발