예전글들
XML문서 생성, 수정 예제
진트
2008. 9. 16. 10:33
XML문서 생성, 수정 예제
XML 문서 → DOM(메모리상의 tree구조화) → java
JDOM을 통한 xml 문서 생성하기
- import org.jdom.*;
import org.jdom.output.*;
import java.io.*; - class JDOMTest3{
public static void main(String[] args) {
Element products = new Element("Products");
Element computer = new Element("computer");
Element ram = new Element("RAM");
Element hdd = new Element("HDD");
Element vga = new Element("VGA");
computer.setAttribute("cpu","4G");
ram.setText("1G");
hdd.setText("200G");
vga.setText("geforce"); - computer.addContent(ram);
computer.addContent(hdd);
computer.addContent(vga);
//root에 computer엘리먼트 추가
products.addContent("4강의강");
products.addContent(computer);
//Document추가 , root.getChildText,
Document doc = new Document(products);
XMLOutputter out = new XMLOutputter();
Format f = out.getFormat();
f.setEncoding("euc-kr");//한글처리 - //개행과 들여쓰기를 함께 해야함
f.setLineSeparator("\n");//개행
f.setIndent(" ");//들여쓰기
f.setTextMode(Format.TextMode.TRIM);//Text에 의한 자동 줄바꿈해제 - out.setFormat(f); //새로운 Format으로 설정
try{
// out.output(doc, System.out);
out.output(doc, new FileWriter("products.xml"));//파일 생성됨
}catch(Exception e){}
}
}
이미 존재하고 있는 xml 문서를 읽어 오기
SAXBuiler생성자에
build 메서드를 이용해서 xml 문서를 이용할수 있다.
/
**앞으로 추세가 sax를 사용하지 않음,
Dom parser는 (xml 문서를 읽어들여 Tree구조로 만드는 작업, 느림),이미객체화됨
/
SAXBuiler물리적으로 존재하는 xml 을 읽어 들여서 사용,
처음 읽어 들이는 속도는 빠르나 특정 엘리먼트를 다시읽어 들일때 속도가 느림
****jdom특징
=>처음 읽어 들일때는 SAXBuiler를 사용하고 다음부터는 DOM을 사용
========================================================================
- import org.jdom.*;
import org.jdom.output.*;
import java.io.*;
import java.util.*;
import org.jdom.input.*;
class JDOMTest4{
public static void main(String[] args) throws Exception{
//이미 물리적으로 존재하는 xml문서 로딩작업
//jdom은 읽어 들일때는 SAX를 사용하고
//Document로 전달할때는 DOM을 사용한다.
SAXBuilder sax= new SAXBuilder();
Document doc = sax.build("products.xml");
Element root = doc.getRootElement();
Element com = new Element("computer");
Element ram = new Element("RAM");
Element hdd = new Element("HDD");
Element vga = new Element("VGA");
com.setAttribute("cpu","4.G");
ram.setText("2G");
hdd.setText("350G");
vga.setText("Goforce34"); - root.addContent(com);
com.addContent(ram);
com.addContent(hdd);
com.addContent(vga);
//Element child1 = root.getChild("computer");//하나밖에 없을경우
//루트 엘리먼트 내에 있는 자식들중 이름이 computer라는
//엘리먼트들만java.util.List구조로 받아낸다.
List<Element> ch = root.getChildren("computer");
for(Element e : ch){
System.out.println(e.getAttribute("cpu"));
} - XMLOutputter out = new XMLOutputter();
Format f = out.getFormat();
f.setEncoding("euc-kr");//한글처리 - //개행과 들여쓰기를 함께 해야함
f.setLineSeparator("\n");//개행
f.setIndent(" ");//들여쓰기
f.setTextMode(Format.TextMode.TRIM);//Text에 의한 자동 줄바꿈해제 - out.setFormat(f); //새로운 Format으로 설정
try{
// out.output(doc, System.out);
out.output(doc, new FileWriter("products.xml"));//파일 생성됨
}catch(Exception e){}
}
}
참고자료
이 글은 스프링노트에서 작성되었습니다.