导入dom4j.jar包
该包需要你去下载。
创建xml文件
XMLWriter writer = null;// 声明写XML的对象
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");// 设置XML文件的编码格式
String filePath = "F://student.xml";//保存xml文件路径
File file = new File(filePath);
Document _document = DocumentHelper.createDocument();
Element _root = _document.addElement("学生信息");//----------根
Element student = _root.addElement("学生");
Element _id = student.addElement("编号");
_id.setText("001");
Element _name = student.addElement("姓名");
_name.setText("灰机");
Element _age = student.addElement("年龄");
_age.setText("18");
for(int i=0;i<5;i++) {
Element _student = _root.addElement("record");
_student.addAttribute("sid", "00"+i);
_student.addAttribute("phone", "1100"+i);
}
try
{
writer = new XMLWriter(new FileWriter(file), format);
writer.write(_document);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("操作结束! ");
生成结果图:
读取xml文件
SAXReader reader = new SAXReader();
String filePath = "f://student.xml";
File file = new File(filePath);
Document document;
try {
document = reader.read(file);
Element root = document.getRootElement();// 得到根节点
/*Element database = (Element)root.selectSingleNode("//学生信息/学生");
List list = database.elements(); //得到database元素下的子元素集合
for(Object obj:list){
Element element = (Element)obj;
//getName()是元素名,getText()是元素值
System.out.println(element.getName()+": "+element.getText());
}*/
List nodes = root.elements("学生");
for (Iterator it = nodes.iterator(); it.hasNext();) {
Element elm = (Element) it.next();
for(Iterator it2=elm.elementIterator();it2.hasNext();){
Element elel=(Element)it2.next();
System.out.println(elel.getName()+":"+elel.getText()+":");
}
}
for (Iterator i = root.elementIterator("record"); i.hasNext();) //对所有record子节点进行遍历
{
Element student = (Element) i.next();
//if (student.attributeValue("sid").equals("001")) //如果record属性sid的值等于001
for(Iterator it= student.attributeIterator();it.hasNext();)//获取record节点的所有属性
{
Attribute attribute = (Attribute) it.next();
String name=attribute.getName();//获取属性名
String text=attribute.getText();//获取属性值
System.out.println(name + " :"+text);
}
}
} catch (DocumentException e) {
e.printStackTrace();
}
本篇文档便于可读,所以采用对照式编码格式。
---这是一个能教你学会Java编程的微信公众号:kaigexuetang_com(长按可复制关注)