您的位置:首页 > 其它

JDOM解析XML

2014-02-17 06:26 113 查看
首先到http://www.jdom.org/下载jdom开发包,点Downloads下的Binaries链接即可转到下载页面。

1.利用jdom写xml文件:





WriteXML.java:

package org.study;

import java.io.File;
import java.io.FileOutputStream;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.XMLOutputter;

public class WriteXML {

public static void main(String[] args) throws Exception {

Element addresslist=new Element("addresslist");
Element linkman_01=new Element("linkman");
Element linkman_02=new Element("linkman");
Element name_01=new Element("name");
Element name_02=new Element("name");
Element email_01=new Element("email");
Element email_02=new Element("email");

Attribute id_01=new Attribute("id","zwj");
Attribute firstName_01=new Attribute("firstName","张");
Attribute id_02=new Attribute("id","zzr");
Attribute firstName_02=new Attribute("firstName","周");

Document doc=new Document(addresslist);

name_01.setText("张无忌");
name_01.setAttribute(id_01);
name_01.setAttribute(firstName_01);
email_01.setText("zhangwuji@gmail.com");

name_02.setText("周芷若");
name_02.setAttribute(id_02);
name_02.setAttribute(firstName_02);
email_02.setText("zhouzhiruo@gmail.com");

linkman_01.addContent(name_01);
linkman_01.addContent(email_01);

linkman_02.addContent(name_02);
linkman_02.addContent(email_02);

addresslist.addContent(linkman_01);
addresslist.addContent(linkman_02);

XMLOutputter out=new XMLOutputter();
out.output(doc,new FileOutputStream(new File("d:"+File.separator+"output.xml")));
}

}


程序运行后,在d盘生成一个output.xml文件,用浏览器打开:



===================================================================================================

2.利用jdom读xml文件:

我们利用jdom读刚才在d盘生成的xml文件。

ReadXML.java:

package org.study;

import java.io.File;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

public class ReadXML {

public static void main(String[] args) throws Exception {

SAXBuilder builder=new SAXBuilder();
Document doc=builder.build(new File("d:"+File.separator+"output.xml"));
Element root=doc.getRootElement();
List<Element> list=root.getChildren("linkman");
for(int i=0;i<list.size();i++){
Element e=list.get(i);
String name=e.getChildText("name");
String id=e.getChild("name").getAttribute("id").getValue();
String firstName=e.getChild("name").getAttribute("firstName").getValue();
String email=e.getChildText("email");
System.out.println("姓名:"+name);
System.out.println("id:"+id);
System.out.println("firstName:"+firstName);
System.out.println("邮箱:"+email);
System.out.println("-------------------------------------------");
}
}

}


运行程序控制台输出:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: