2013년 8월 13일 화요일

JAVA DOM 예제

import java.io.*;
import javax.xml.parsers.*; //XML 파서를 다루기 위한것
import org.w3c.dom.*;       //DOM
import com.sun.xml.tree.*;
class DomSampleJava {
 public static void main(String[] args) throws Exception{
  //아래는 DOM을 준비하는 부분이다.
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
 
  // 문서를 읽음, JAXP RI에 DocumentBuilder의
 //parse 메소드를 부른다.이 이후부터 문서를 객체화하여 doc라는 이름으로 접근 할 수 있다.
  Document doc = db.parse(new FileInputStream("DomSampleJava.xml"));
 //문서를 써낸다., 파서의 내장 클래스 라이브러리, //파일을 써낼때 이용
  Document xdoc = (Document)doc;
  BufferedWriter bw = new BufferedWriter(new FileWriter("result.xml"));
  xdoc.write(bw, "euc-kr");
  bw.close();
 }
}
 
 
 
[DomSampleJava.xml]
<?xml version="1.0" encoding="euc-kr" ?>
<cars>
 <car>
  <name>승용차</name>
  <price>150</price>
 </car>
 <car>
  <name>트럭</name>
  <price>500</price>
 </car>
 </cars>
 

댓글 없음:

댓글 쓰기