package com.shift.gef.xml;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
/**
* JDOM을 이용한 XML파싱.
* @author jw choi
*/
public class JDomSample {
/**
* @param args
*/
public static void main(String[] args) {
SAXBuilder builder = new SAXBuilder();
Document doc = null;
try {
doc = builder.build(new File("c:/project/xml/test_org.xml"));
} catch (IOException ioe) {
System.out.println("IOException : " + ioe.fillInStackTrace());
} catch (JDOMException jdome) {
System.out.println("JDOMException : " + jdome.fillInStackTrace());
}
Element root = doc.getRootElement();
/** ROOT전체 파싱 **/
nodeParser(root);
/** 특정 노드 리스트를 파싱 **/
// List sqlElement = root.getChildren("sql");
// getSQL(root, "RETRIEVE_SAMEPLE2");
}
/**
* 지정한 쿼리를 XML에서 반환하는 메소드.
* @param p_root
* @param p_sql
* @return
*/
public static String getSQL(Element p_root, String p_sql) {
List sqlElement = p_root.getChildren("sql");
for (int i=0; i<sqlElement.size(); i++) {
Element e = (Element)sqlElement.get(i);
if(e.getAttributeValue("name").equals(p_sql)) {
return e.getChildText("query");
}
}
return null;
}
/**
* XML노드를 파싱.
* @param p_el XML Node Element
*/
public static void nodeParser(Element p_el) {
List list = p_el.getChildren();
Iterator it = list.iterator();
while(it.hasNext()) {
Element e = (Element)it.next();
List att = e.getAttributes();
if (att.size() != 0) {
Iterator i = att.iterator();
while(i.hasNext()) {
/** Attribute 파싱 **/
Attribute at = (Attribute)i.next();
System.out.println("node : " + e.getName());
System.out.println("attribute : " + at.getName() +" attribute value : " + at.getValue());
}
}
List li = e.getChildren();
if (li.size() != 0) {
nodeParser(e); /** recursive call **/
} else {
/** 노드의 값이 있는 경우에만 출력 **/
if (!e.getValue().trim().equals("")) {
System.out.println("parent node : " + e.getParentElement().getName() + " current node : " + e.getName());
System.out.println("value : " + e.getValue());
}
}
}
}
}
No comments:
Post a Comment