首先要導入jdom的jar包dom
//寫xmlui
public class WriteXML {
public static void main(String[] args) throws FileNotFoundException, IOException {
Element addressList=new Element("addressList");
Element linkman=new Element("linkman");
Element name=new Element("name");
Element email=new Element("email");
Attribute id = new Attribute("id","lxh") ;
// 定義Document對象
Document doc=new Document(addressList);
name.setText("小李");
// 將屬性設置到元素之中
name.setAttribute(id);
email.setText("qq@163.com");
// 設置關係
linkman.addContent(name);
linkman.addContent(email);
addressList.addContent(linkman);
XMLOutputter out=new XMLOutputter();
//設置編碼
out.setFormat(out.getFormat().setEncoding("GBK"));
File file=new File("D:"+File.separator+"address.xml");
out.output(doc,new FileOutputStream(file));
}
}編碼
讀xmlorm
public class ReadXML {
public static void main(String[] args) throws JDOMException, IOException {
SAXBuilder builder = new SAXBuilder() ;
File file=new File("D:"+File.separator+"address.xml");
Document read_doc = builder.build(file) ;
Element root = read_doc.getRootElement() ; // 取得根
List list = root.getChildren("linkman") ; // 獲得全部的linkman
for(int x=0;x<list.size();x++){
Element e = (Element) list.get(x) ;
String name = e.getChildText("name") ; // 獲得name子節點的內容
String id = e.getChild("name").getAttribute("id").getValue() ;
String email = e.getChildText("email") ;
System.out.println("-------------- 聯繫人 -------------") ;
System.out.println("姓名:" + name + ",編號:" + id) ;
System.out.println("EMAIL:" + email) ;
System.out.println("-----------------------------------") ;
System.out.println() ;
}
}
}xml