用jdom解析
package jdom;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
publicclass jdom {
privatestatic String xmlpath = "jdom.xml";
publicstaticvoid main(String[] args) throws Exception{
//resolving();
createXml();
}
publicstatic void createXml() throws Exception{
//创建document对象
Document document = new Document();
//创建根节点
Element root = new Element("students");
//将根节点添加到document对象中
document.addContent(root);
for(int i = 0 ;i < 20 ; i++){
//创建根元素节点
Element student = new Element("student");
//声明参数ID
String id ="";
for(int j = 0; j< 9 ; j ++ ){
id += new Random().nextInt(8)+1;
}
//设置跟元素节点的属性
student.setAttribute("id",id);
//将根元素节点添加到根节点中
root.addContent(student);
//声明一个姓名的数组
String nameList[] = {"吕布","赵云","马超","张飞","关羽","许褚","孙策","周瑜","夏侯渊","张颌","于禁","黄忠","典韦","曹仁","程普"};
String sexList[] = {"男","女"};
//创建元素节点
Element name = new Element("name");
Element sex = new Element("sex");
Element age =new Element("age");
Element phone = new Element("phone");
//设置根元素节点的文本值
name.setText(nameList[new Random().nextInt(nameList.length)]);
sex.setText(sexList[new Random().nextInt(sexList.length)]);
age.setText(new Random().nextInt(20)+20+"");
String tel ="";
for(int k = 0; k< 7 ; k++ ){
tel += new Random().nextInt(9);
}
phone.setText("0756-"+tel);
//将元素节点添加到根元素节点中
student.addContent(name);
student.addContent(sex);
student.addContent(age);
student.addContent(phone);
}
//设置XML输出排版
Format format = Format.getPrettyFormat();
XMLOutputter out = new XMLOutputter(format);
out.output(document, new FileOutputStream(xmlpath));
}
//解析XML文档
@SuppressWarnings("rawtypes")
publicstaticvoid resolving() throws Exception{
//获取XML解析器
SAXBuilder builder = new SAXBuilder();
//获取document对象
Document doucment = builder.build(xmlpath);
//获取根节点
Element students = doucment.getRootElement();
//获取根元素节点
List studentList = students.getChildren("student");
for(int i = 0 ; i< studentList.size() ; i++ ){
Element student = (Element)studentList.get(i);
System.out.println("id = "+student.getAttributeValue("id")+" name = "
+student.getChildText("name")+" sex = "
+student.getChildText("sex")+" age = "
+student.getChildText("age")+" phone = "
+student.getChildText("phone"));
}
System.err.println("\n---------------------------------------------------------------------");
for(Iterator iter=studentList.iterator();iter.hasNext();){
Element student = (Element)iter.next();
System.out.println("id = "+student.getAttributeValue("id")+" name = "
+student.getChildText("name")+" sex = "
+student.getChildText("sex")+" age = "
+student.getChildText("age")+" phone = "
+student.getChildText("phone"));
}
}
}
原文链接:https://www.f2er.com/xml/298304.html