본문 바로가기
카테고리 없음

JDom 으로 XML생성하기

by eqzero 2006. 7. 26.

HtmlParseTest .java

======================================

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class HtmlParseTest {

 public static void main(String[] args) {
  try {
   Element root = new Element("JavaBook"); //Root를 생성
  

  // 루프를 돌면서 엘리멘트를 생성하고 root에 붙인다.
   for (int i = 1; i <= 5; i++)
   {
    Element fiE = new Element("JavaBook"+i);
    fiE.setAttribute("index" , String.valueOf(i)); //어트리뷰트를 설정한다.
    fiE.setText("Title "+i); // 데이터를 삽입

    root.addContent(fiE);
   }
   Document doc = new Document(root);


   XMLOutputter xmlOut = new XMLOutputter();
   Format format = Format.getPrettyFormat();
   xmlOut.setFormat(format);

   xmlOut.output(doc , System.out);

  } catch (Exception e) {
   // TODO: handle exception
   e.printStackTrace();
  }

 }
}

출력

======================================

<?xml version="1.0" encoding="UTF-8"?>
<JavaBook>
  <JavaBook1 index="1">Title 1</JavaBook1>
  <JavaBook2 index="2">Title 2</JavaBook2>
  <JavaBook3 index="3">Title 3</JavaBook3>
  <JavaBook4 index="4">Title 4</JavaBook4>
  <JavaBook5 index="5">Title 5</JavaBook5>
</JavaBook>

======================================

출처 ; http://cafe.naver.com/ArticleRead.nhn?clubid=10153147&menuid=58&boardtype=L&page=&articleid=8212