dom4j 对xml操作

package com.wasu.var.common.util;

import  java.io.File;   
import  java.io.FileWriter;   
import  java.util.Iterator;   

import  org.dom4j.Document;   
import  org.dom4j.DocumentHelper;   
import  org.dom4j.Element;   
import  org.dom4j.io.OutputFormat;   
import  org.dom4j.io.SAXReader;   
import  org.dom4j.io.XMLWriter;   

public   class  createXML   {

   
public static void create(String filename){
try{
Document document = DocumentHelper.createDocument();
Element root = document.addElement("学生信息");

Element element=null;
Element name=null;
Element age=null;
for(int i=0;i<100;i++){
    element=root.addElement("学生");
    name = element.addElement("学生编号");
name.setText("No"+i);
name = element.addElement("学生名字");
name.setText("Name"+i);
name = element.addElement("学生年龄");
name.setText("Age"+i);
}
OutputFormat format = OutputFormat.createPrettyPrint();
format = OutputFormat.createCompactFormat();
format.setEncoding("GBK");
XMLWriter writer = new XMLWriter(new FileWriter(new File(filename)), format);
writer.write(document);
writer.close();
}catch(Exception e){
e.printStackTrace();
}
}
public static void read(String filename){
File file = new File(filename);
if(file.exists()){
try{
SAXReader reader = new SAXReader();
Document document = reader.read(file);
Element root = document.getRootElement();// 得到根节点
for (Iterator i = root.elementIterator("学生"); i.hasNext();) {
                Element student = (Element) i.next();
                    System.out.println("学生编号="+student.selectSingleNode("学生编号").getText());
                    System.out.println("学生名字="+student.selectSingleNode("学生名字").getText());
                    System.out.println("学生年龄="+student.selectSingleNode("学生年龄").getText());
                    System.out.println();
 
            }
}catch(Exception e){
e.printStackTrace();
}

}else{
System.out.println("文件找不到");
}
}
public static void main(String args[]){
String filename ="e://bbc/abc.xml";
create(filename);
read(filename);
}
}    

你可能感兴趣的:(xml)