Thursday, July 02, 2009

JDOM을 사용한 XML문서 작성

 

JDOM을 사용한 간단한 XML문서 작성하는 방법.
 
 - 아래 소스를 참고 ㅎㅎ
 
import java.io.FileWriter;
import java.io.IOException;
import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class JDomCreateXml {
 /**
  * @param args
  */
 public static void main(String[] args) {
  Element rootElement = new Element("root");
  Document doc = new Document(rootElement);
  rootElement.setAttribute(new Attribute("속성", "여긴 속성값"));
  rootElement.addContent(new Element("메이커").addContent("현대"));
  rootElement.addContent(new Element("모델").addContent("아반떼XD"));
  rootElement.addContent(new Element("년식").addContent("2006"));
  rootElement.addContent(new Element("색상").addContent("silver"));
  rootElement.addContent(new Element("품번").addContent("HD200601"));
  rootElement.addContent(new Comment("주석이 들어갈 부분 "));
 
  /** 특정 노드를 제거 **/
  Element yearElement = rootElement.getChild("년식");
  boolean removed = rootElement.removeChild("년식");
 
  /** XML Write **/
  Format f = Format.getCompactFormat();
  f.setEncoding("euc-kr");
  f.setIndent("    ");
  XMLOutputter outputter = new XMLOutputter(f);
  try {
   FileWriter writer = new FileWriter("c:/project/xml/jdom_test.xml");
   outputter.output(doc, writer);
   writer.close();
  } catch(IOException ioe ) {
   System.out.println("IOE : " + ioe.fillInStackTrace());
  }
 }
}

No comments: