码迷,mamicode.com
首页 > 其他好文 > 详细

Xml-Jdom的使用

时间:2017-01-13 07:47:32      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:list   row   img   ddc   static   address   uil   getchildt   ext   

技术分享

首先要导入jdom的jar包

//写xml

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));



}
}

读xml

 

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-Jdom的使用

标签:list   row   img   ddc   static   address   uil   getchildt   ext   

原文地址:http://www.cnblogs.com/jrts/p/6280480.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!