今天突然想到在Java中還沒用過XML方面的東西,于是找了些資料看,終于成功的寫了個Demo將XML插入數(shù)據(jù)庫及將數(shù)據(jù)庫表數(shù)據(jù)讀出轉(zhuǎn)成XML文件,XML的內(nèi)容太多了,這僅僅是個利用JDom組件完成的非常簡單的程序

2006年7月7日
最近的工作常常要和XML格式的文檔或字符串打交道,發(fā)現(xiàn)用JDOM來做真是方便。可以實現(xiàn)XML應用程序的快速開發(fā)。
在 JDOM 中,XML 元素就是 Element 的實例,XML 屬性就是 Attribute 的實例,XML 文檔本身就是 Document 的實例。
因為 JDOM 對象就是像 Document、Element 和 Attribute 這些類的直接實例,因此創(chuàng)建一個新 JDOM 對象就如在 Java 語言中使用 new 操作符一樣容易。JDOM 的使用是直截了當?shù)摹?br> JDOM 使用標準的 Java 編碼模式。只要有可能,它使用 Java new 操作符而不故弄玄虛使用復雜的工廠化模式,使對象操作即便對于初學用戶也很方便。
本文分兩步對JDOM的應用加以介紹:XML創(chuàng)建 和 XML解析
一、XML文檔創(chuàng)建
我們由零開始利用JDOM生成一個XML文檔。最后的結(jié)果(樣本文檔)看起來象這樣:
<?xml version="1.0" encoding="UTF-8"?>
<MyInfo comment="introduce myself">
<name>kingwong</name>
<sex value="male"/>
<contact>
<telephone>87654321</telephone>
</contact>
</MyInfo>
1.以 MyInfo 為根元素創(chuàng)建文檔
Element rootElement = new Element("MyInfo");//所有的XML元素都是 Element 的實例。根元素也不例外:)
Document myDocument = new Document(rootElement);//以根元素作為參數(shù)創(chuàng)建Document對象。一個Document只有一個根,即root元素。
2.給根元素添加屬性
Attribute rootAttri = new Attribute("comment","introduce myself");//創(chuàng)建名為 commnet,值為 introduce myself 的屬性。
rootElement.setAttribute(rootAttri);//將剛創(chuàng)建的屬性添加到根元素。
這兩行代碼你也可以合成一行來寫,象這樣:
rootElement.setAttribute(new Attribute("comment","introduce myself"));
或者
rootElement.setAttribute("comment","introduce myself");
3.添加元素和子元素
JDOM里子元素是作為 content(內(nèi)容)添加到父元素里面去的,所謂content就是類似上面樣本文檔中<name></name>之間的東東,即kingwong。羅嗦了點是吧:)
Element nameElement = new Element("name");//創(chuàng)建 name 元素
nameElement.addContent("kingwong");//將kingwong作為content添加到name元素
rootElement.addContent(nameElement);//將name元素作為content添加到根元素
這三行你也可以合為一句,象這樣:
rootElement.addContent((Content)(new Element("name").addContent("kingwong")));//因為addContent(Content child)方法返回的是一個Parent接口,而Element類同時繼承了Content類和實現(xiàn)了Parent接口,所以我們把它造型成Content。
我們用同樣的方法添加帶屬性的子元素<sex value="male"/>
rootElement.addContent(new Element("sex").setAttribute("value","male"));//注意這里不需要轉(zhuǎn)型,因為addAttribute(String name,String value)返回值就是一個 Element。
同樣的,我們添加<contract />元素到根元素下,用法上一樣,只是稍微復雜了一些:
rootElement.addContent((Content)(new Element("contact").addContent((Content)(new Element("telephone").addContent("87654321")))));
如果你對這種簡寫形式還不太習慣,你完全可以分步來做,就象本節(jié)剛開始的時候一樣。事實上如果層次比較多,寫成分步的形式更清晰些,也不容易出錯。
4.刪除子元素
這個操作比較簡單:
rootElement.removeChild("sex");//該方法返回一個布爾值
到目前為止,我們學習了一下JDOM文檔生成操作。上面建立了一個樣本文檔,可是我們怎么知道對不對呢?因此需要輸出來看一下。我們將JDOM生成的文檔輸出到控制臺,使用 JDOM 的 XMLOutputter 類。
5. 將 JDOM 轉(zhuǎn)化為 XML 文本
XMLOutputter xmlOut = new XMLOutputter(" ",true);
try {
xmlOut.output(myDocument,System.out);
} catch (IOException e) {
e.printStackTrace();
}
XMLOutputter 有幾個格式選項。這里我們已指定希望子元素從父元素縮進兩個空格,并且希望元素間有空行。
new XMLOutputter(java.lang.String indent, boolean newlines)這個方法在最新版本中已經(jīng)不建議使用。JDOM有一個專門的用來定義格式化輸出的類:org.jdom.output.Format,如果你沒有特殊的要求,有時候使用里面的幾個靜態(tài)方法(應該可以說是預定義格式)如 getPrettyFormat()就可以了。我們把上面的輸出格式稍微改一下,就象這樣:
XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat());
6.將JDOM文檔轉(zhuǎn)化為其他形式
XMLOutputter 還可輸出到 Writer 或 OutputStream。為了輸出JDOM文檔到一個文本文件,我們可以這樣做:
FileWriter writer = new FileWriter("/some/directory/myFile.xml");
outputter.output(myDocument, writer);
writer.close();
XMLOutputter 還可輸出到字符串,以便程序后面進行再處理:
Strng outString = xmlOut.outputString(myDocument);
當然,在輸出的時候你不一定要輸出所有的整個文檔,你可以選擇元素進行輸出:
xmlOut.output(rootElement.getChild("name"),System.out);
一句話,JDOM非常靈活方便!如果你想進一步研究JDOM,請到官方網(wǎng)站去看一看:http://www.jdom.org
本節(jié)示例源碼:
package com.cyberobject.study;
import java.io.IOException;
import org.jdom.Attribute;
import org.jdom.Content;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
/**
* @author kingwong
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class TestJDOM {
public static void main(String[] args)
{
Element rootElement = new Element("MyInfo");
Document myDocument = new Document(rootElement);
// Attribute rootAttri = new Attribute("comment","introduce myself");
// rootElement.setAttribute(rootAttri);
rootElement.setAttribute("comment","introduce myself");
//rootElement.setAttribute(new Attribute("comment","introduce myself"));
// Element sexElement = new Element("sex");
// rootElement.addContent(sexElement);
// Element nameElement = new Element("name");
// nameElement.addContent("kingwong");
// rootElement.addContent(nameElement);
rootElement.addContent((Content)(new Element("name").addContent("kingwong")));
rootElement.addContent(new Element("sex").setAttribute("value","male"));
rootElement.addContent((Content)(new Element("contract").addContent((Content)(new Element("telephone").addContent("87654321")))));
rootElement.removeChild("sex");
XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat());
try {
xmlOut.output(myDocument,System.out);
//xmlOut.output(rootElement.getChild("name"),System.out);
//String outString = xmlOut.outputString(myDocument);
} catch (IOException e) {
e.printStackTrace();
}
}
}
二、XML文檔解析
JDOM 不光可以很方便的建立XML文檔,它的另一個用處是它能夠讀取并操作現(xiàn)有的 XML 數(shù)據(jù)。
JDOM的解析器在org.jdom.input.*這個包里,其中的DOMBuilder的功能是將DOM模型的Document解析成JDOM模型的Document;SAXBuilder的功能是從文件或流中解析出符合JDOM模型的XML樹。由于我們經(jīng)常要從一個文件里讀取數(shù)據(jù),因此我們應該采用后者作為解析工具。
解析一個xml文檔,基本可以看成以下幾個步驟:
1.實例化一個合適的解析器對象
本例中我們使用SAXBuilder:
SAXBuilder sb = new SAXBuilder();
2.以包含XML數(shù)據(jù)的文件為參數(shù),構(gòu)建一個文檔對象myDocument
Document myDocument = sb.build(/some/directory/myFile.xml);
3.獲到根元素
Element rootElement = myDocument.getRootElement();
一旦你獲取了根元素,你就可以很方便地對它下面的子元素進行操作了,下面對Element對象的一些常用方法作一下簡單說明:
getChild("childname") 返回指定名字的子節(jié)點,如果同一級有多個同名子節(jié)點,則只返回第一個;如果沒有返回null值。
getChildren("childname") 返回指定名字的子節(jié)點List集合。這樣你就可以遍歷所有的同一級同名子節(jié)點。
getAttributeValue("name") 返回指定屬性名字的值。如果沒有該屬性則返回null,有該屬性但是值為空,則返回空字符串。
getChildText("childname") 返回指定子節(jié)點的內(nèi)容文本值。
getText() 返回該元素的內(nèi)容文本值。
還有其他沒有羅列出來的方法,如果需要的話,可以隨時查閱JDOM的在線文檔:http://www.jdom.org/docs/apidocs/index.html。當然你可以在你需要的地方添加、刪除元素操作,還記得上面的創(chuàng)建XML的方法嗎?呵呵~~~
學習新東東還是從實例學起最為快捷,下面簡單舉個例子,就以上面的XML樣本代碼來學習JDOM的XML解析。本例中讀取了樣本XML文件里一些屬性和content,最后我們還在contact元素里插入了一個新元素<email value="wanghua@cyberobject.com" />。盡管我們實現(xiàn)了對于XML的基本操作,細心的朋友可能會
有疑問:如果XML文檔的層次稍微復雜一些,如果嵌套多達幾十上百層的話(開個玩笑),如果靠這樣從根元素一級一級地通過getChild("childname")來訪問子元素的話,將會非常痛苦!是的,的確是這樣,但是我們有另一個有力的工具XPath,為什么不用呢?這是后話!先賣個關子(手敲累啦,下回吧,呵呵)。
/*
* Created on 2004-8-21
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.cyberobject.study;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
/**
* @author kingwong
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class TestJDOM2 {
public static void main(String[] args){
SAXBuilder sb = new SAXBuilder();
try
{
Document doc = sb.build("myFile.xml");
Element root = doc.getRootElement();
String str1 = root.getAttributeValue("comment");
System.out.println("Root Element's comment attribute is : " + str1);
String str2 = root.getChild("sex").getAttributeValue("value");
System.out.println("sex Element's value attribute is : " + str2);
String str3 = root.getChildText("name");
System.out.println("name Element's content is :" + str3);
String str4 = root.getChild("contact").getChildText("telephone");
System.out.println("contact Element's telephone subelement content is : " + str4 + "\n");
Element inputElement = root.getChild("contact");
inputElement.addContent(new Element("email").setAttribute("value","wanghua@cyberobject.com"));
XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat());
String outStr = xmlOut.outputString(root);
System.out.println(outStr);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
使用DOM方式,Java解析XML基本步驟:
首先,我們需要建立一個解析器工廠。
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
然后可以利用這個工廠來獲得一個具體的解析對象。
DocumentBuilder builder=dbf.newDocumentBuilder();
DocumentBuilder的Parse()方法接受一個XML文檔名作為輸入?yún)?shù),返回一個Document對象。Document對象代表了 一個XML文檔的樹模型。
Document doc=builder.parse("candiate.xml");
使用Document對象的getElementsByTagName()方法,我們可以得到一個NodeList對象,他是XML文檔中的標簽元素 列表,可以使用NodeList對象的item()方法來得列表中的每一個Node對象。
NodeList nl=doc.getElementsByTagName("PERSON");
Element node=(Element)nl.item(i);
最后,我們會使用Node對象的getNodeValue()方法提取某個標簽內(nèi)的內(nèi)容。
node.getElementsByTagName("NAME").item(0).getFirstChild().getNodeValue()
完整程序代碼:
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class dom {
public static void main(String args[]){
String uri=args[0];
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();//建立一個解析器工廠。
DocumentBuilder builder=factory.newDocumentBuilder();//獲得一個具體的解析對象。
Document doc=builder.parse(uri);//返回一個Document對象。
System.out.println(doc.getImplementation());
NodeList nl =doc.getElementsByTagName("PERSON");//得到一個NodeList對象。
for (int i=0;i<nl.getLength();i++){
Element node=(Element) nl.item(i);//得列表中的每一個Node對象。
System.out.print("NAME: ");
System.out.println (node.getElementsByTagName("NAME").item(0).getFirstChild().getNodeValue());
System.out.print("ADDRESS: ");
System.out.println (node.getElementsByTagName("ADDRESS").item(0).getFirstChild().getNodeValue());
System.out.print("TEL: ");
System.out.println (node.getElementsByTagName("TEL").item(0).getFirstChild().getNodeValue());
System.out.print("FAX: ");
System.out.println (node.getElementsByTagName("FAX").item(0).getFirstChild().getNodeValue());
System.out.print("EMAIL: ");
System.out.println (node.getElementsByTagName("EMAIL").item(0).getFirstChild().getNodeValue());
System.out.println();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
附將數(shù)據(jù)庫表轉(zhuǎn)成XML文件代碼: 表tmpinfo字段
(id,username,password,sex,officephone,mobile,homephone,corpaddress,homeaddress)
public class ExtraTableToXML
{
public void BuildXMLDoc()
{
Connection conn = null;
ResultSet rst = null;
Statement stmt = null;
try
{
conn = ConnectionFactory.getInstance().getConnection();
stmt = conn.createStatement();
rst = stmt.executeQuery("select * from tmpinfo");
}
catch (Exception sqlException)
{
System.out.println("數(shù)據(jù)庫操作錯誤");
}
try
{
Document document = new Document(new Element("AllUserInfo"));
ResultSetMetaData rsmd = rst.getMetaData(); //取得字段名
String colName = "";
int i = 0;
int numOfColumns = rsmd.getColumnCount();
while (rst.next())
{
Element element0 = new Element("userinfo");
document.getDocument().getRootElement().addContent(element0);
Element element1 = new Element("phone");
element0.addContent(element1);
Element element2 = new Element("address");
element0.addContent(element2);
for (i = 1; i < numOfColumns; i++)
{
colName = rst.getString(i);
if (i > 4 && i < 8)
{
Element element = new Element(rsmd.getColumnName(i))
.setText(colName);
element1.addContent(element);
}
else if (i > 7 && i < 9)
{
Element element = new Element(rsmd.getColumnName(i))
.setText(colName);
element2.addContent(element);
}
else
{
Element element = new Element(rsmd.getColumnName(i)).setText(colName);
element0.addContent(element);
}
}
XMLOutputter outp = new XMLOutputter(Format.getPrettyFormat());
outp.output(document, new FileOutputStream("c:\\userinfo.xml"));
}
}
catch (Exception e)
{
System.out.println("XML文檔生成錯誤!");
}
}
}
讀取XML文件插入數(shù)據(jù)庫表,表同上述,即tmpinfo
public void ReadXMLToTable()
{
try
{
//從文件或流中解析出符合JDom模型的XML樹
SAXBuilder sb = new SAXBuilder();
//構(gòu)建一個文檔對象
Document doc = sb.build("c:\\userinfo.xml");
//獲得根元素
Element rootElement = doc.getRootElement();
String id="",username="",password="";
String sex="",officephone="",mobile="";
String homephone="",corpaddress="",homeaddress="";
Element element = null;
Element element1 = null;
Element element2 = null;
List list = null;
List list1 = null;
List list2 = null;
//獲得指定名字的子節(jié)點List集合
list = rootElement.getChildren("userinfo");
for(int i=0;i<list.size();i++)
{
//userinfo節(jié)點子元素
element = (Element)list.get(i);
id=element.getChildText("id");
username=element.getChildText("username");
password=element.getChildText("password");
sex=element.getChildText("sex");
//phone子節(jié)點List集合
list1 = element.getChildren("phone");
for(int j=0;j<list1.size();j++)
{
//phone子節(jié)點元素
element1 = (Element)list1.get(j);
officephone = element1.getChildText("officephone");
mobile = element1.getChildText("mobile");
homephone = element1.getChildText("homephone");
}
//address子節(jié)點List集合
list2 = element.getChildren("address");
for(int k=0;k<list2.size();k++)
{
//address子節(jié)點元素
element2 = (Element)list2.get(k);
corpaddress = element2.getChildText("corpaddress");
homeaddress = element2.getChildText("homeaddress");
}
//調(diào)用數(shù)據(jù)DAO類進行插入數(shù)據(jù)
Connection conn = ConnectionFactory.getInstance().getConnection();
PreparedStatement pstmt = null;
try
{
pstmt = conn.prepareStatement("insert into tmpinfo(username,password,sex,officephone,mobile,homephone,corpaddress,homeaddress) values(?,?,?,?,?,?,?,?)");
pstmt.setString(1,username);
pstmt.setString(2,password);
pstmt.setString(3,sex);
pstmt.setString(4,officephone);
pstmt.setString(5,mobile);
pstmt.setString(6,homephone);
pstmt.setString(7,corpaddress);
pstmt.setString(8,homeaddress);
pstmt.execute();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try
{
pstmt.close();
conn.close();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}//for
}
catch (JDOMException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}