Professional Documents
Culture Documents
(三)程式碼撰寫:
import java.io.FileOutputStream;
//載入 JDOM 類別
import org.jdom.*;
//載入用來輸出的 XMLOutputter 類別
import org.jdom.output.XMLOutputer;
public class JdomCreate{
/** 主程式進入點 */
public static void main(String args[]){
try{
/** 新增元素 */
//建立根元素<addressbook>
Element root=new Element(“addressbook”);
//建立子元素<name>與其屬性及內容
Element nameElement=new Element(“name”);
nameElement.addAttribute(“age”,”20”);
nameElement.addContent(“陳志華”);
//Element nicknameElement=new Element(“nickname”);
//nicknameElement.addContent(“ChiHua”);
//nameElement.addContent(nicknameElement);
root.addContent(nameElement);
//建立子元素<address>與其內容
Element addressElement=new Element(“address”);
撰寫者:陳志華
addressElement.addContent(“台北市”);
root.addContent(addressElement);
//建立子元素<telephone>與其內容
Element telephoneElement=new Element(“telephone”);
telephoneElement.addContent(“0911”);
root.addContent(telephoneElement);
/** 修改元素 */
Root.getChild(“name”).setAttribute(“age”,”26”);
Root.getChild(“address”).setContent(“高雄市”);
/** 刪除元素 */
//刪除子元素<telephone>
Boolean removed=root.removeChild(“telephone”);
//刪除所有子元素
//Boolean removed=root.removeChildren();
/** 有效性驗証 */
//建立 DocType 物件
DocType documenttype=new DocType(“addressbook”,”addresbook.dtd”);
//輸出 JDOM 文件
//Document document=new Document(root);
Document document=new Document(root, documenttype);
}
Finally{
File.close();
}
}
}
}
撰寫者:陳志華
二、讀取 XML 文件
(一)使用 SAX 讀取 XML 文件,假設讀取 addressbook.xml
//載入用來輸入的 SAXBuilder 類別
import org.jdom.input.SAXBuilder;
//載入用來輸出的 XMLOutputter
import org.jdom.output.XMLOutputter;
public class SaxJdom{
public static void main(String args[]){
try{
//建立 SAXBuilder
SAXBuilder builder=new SAXBuilder();
//建立 JDOM 文件
Document document=builder.build(new File(“addressbook.xml”));
showDocument(document);
}
catch(Exception e){
e.printStackTrace();
System.exit(1);
}
}
Pubic static void showDocument(Document document) throws IOException{
XMLOutputter outputter=new XMLOutputter();
//以 Big5 編碼輸出
outputter.setEncoding(“Big5”);
outputter.output(document,System.out);
}
}
showDocument(document);
}
catch(Exception e){
e.printStackTrace();
System.exit(1);
}
}
Pubic static void showDocument(Document document) throws IOException{
XMLOutputter outputter=new XMLOutputter();
//以 Big5 編碼輸出
outputter.setEncoding(“Big5”);
outputter.output(document,System.out);
}
}
撰寫者:陳志華