oracle db 에서 데이타를 읽어서 xml을 생성하는 예제
명령행 매개변수로 전달된 상품 정보를 가지고 XML 문서(product.xml)를 생성하는 Java Application 과 만들어
진 XML 문서를 DB 테이블에 CLOB 형으로 저장하는 Java Application 을 작성하세요. XML 문서를 만드는 과정
은 비어 있는 Document 객체에 노드들을 추가하는 방식을 활용하십시오.
[ 명령행 매개변수로 입력하는 상품 정보 ]
상품ID, 상품명, 가격,
다음과 같은 구조로 XML 파일이 생성되도록 구현한다.
<PRODUCTLIST>
<PRODUCT>
<ID>...........</ID>
<NAME>...........</NAME>
<PRICE>...........</PRICE>
</PRODUCT>
</PRODUCTLIST>
- 저장되는 DB 테이블 스펙
테이블명 : xmltable
필드 스펙 : productid char(5), xmlcontent clob
- DB 필드의 CLOB 형 필드에 product.xml 을 저장하는 기능은 PreparedStatement 의 setCharacterStream()
이라는 메서드를 사용한다.
com.noaats.xml000.CreatXML.java
===================================================
package com.noaats.xml000;
import java.io.StringReader;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class CreateXML {
private Document xml;
private String jdbcDriver = "oracle.jdbc.driver.OracleDriver";
private String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:XE";
private String userName = "scott";
private String userPwd = "tiger";
private String insertSql = "insert into xmltable values ( ?,?) ";
/**
* @param args
* 상품정보를 입력 받는다. args[0] id args[1] name args[2] price
*/
public static void main(String[] args) {
CreateXML cxml = new CreateXML(args);
}
public CreateXML(String[] args) {
process(args);
}
protected void process(String[] args) {
if (args.length == 0) {
System.out.println("Usage : CreateXML
} else {
Element product = createXMLDocument();
createID(product, args[0]);
createName(product, args[1]);
createPrice(product, args[2]);
saveXML(args[0], product);
}
}
private void saveXML(String id, Element product) {
Connection conn = null;
PreparedStatement ps = null;
try {
Driver driver = (Driver)Class.forName(jdbcDriver).newInstance();
conn = DriverManager.getConnection(jdbcUrl, userName, userPwd);
} catch (Exception sqle) {
sqle.printStackTrace();
}
TransformerFactory factory = TransformerFactory.newInstance();
try {
StringWriter sw = new StringWriter();
Properties output = new Properties();
output.setProperty(OutputKeys.INDENT, "yes");
Transformer transformer = factory.newTransformer();
transformer.setOutputProperties(output);
transformer.transform(new DOMSource(xml), new StreamResult(sw));
System.out.println(sw.getBuffer().toString());
ps = conn.prepareStatement(insertSql);
ps.setString(1,id);
ps.setCharacterStream(2,new StringReader(sw.getBuffer().toString()),sw.getBuffer().toString().length());
ps.execute();
ps.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (ps != null) ps.close();
if (conn != null ) conn.close();
} catch (Exception ee) {
ee.printStackTrace();
}
}
}
private void createPrice(Element product, String price) {
Element priceElement = createElementWithValue("PRICE", price);
product.appendChild(priceElement);
}
private void createName(Element product, String name) {
Element productElement = createElementWithValue("PRODUCT", name);
product.appendChild(productElement);
}
private void createID(Element product, String id) {
Element idElement = createElementWithValue("ID", id);
// Text idTest = xml.createTextNode(id);
// idElement.appendChild(idTest);
product.appendChild(idElement);
}
private Element createElementWithValue(String elementName,
String elementValue) {
Element element = xml.createElement(elementName);
Text textNode = xml.createTextNode(elementValue);
element.appendChild(textNode);
return element;
}
protected Element createXMLDocument() {
Element product = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
xml = builder.newDocument();
Element productlist = xml.createElement("PRODUCTLIST");
xml.appendChild(productlist);
product = xml.createElement("PRODUCT");
productlist.appendChild(product);
} catch (Exception e) {
e.printStackTrace();
}
return product;
}
}