xml文件的解析有很多方法,其中dom4j是效率相对比较高的,现整理如下:
package parse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Dom4JParse {
private static final String filePath="jdom.xml";
private static final String classPath=Thread.currentThread().getContextClassLoader().getResource("").getPath();
private static SAXReader reader;
private static Document document;
static{
reader=new SAXReader();
try {
File file=new File(classPath+filePath);
Reader r=new InputStreamReader(new FileInputStream(file),"UTF-8");
System.out.println("file --Path---"+file.getPath());
document=reader.read(r);
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void parse(){
Element rootEle=document.getRootElement();
String rootText=rootEle.getName();
System.out.println("root---Name"+rootText);
Element areaEle=rootEle.element("area");
System.out.println("名字----"+areaEle.getName()+" 文本------"+areaEle.getText());
List provinceList=rootEle.elements("province");
for (int i = 0; i < provinceList.size(); i++) {
Element province=(Element) provinceList.get(i);
String proText=province.attributeValue("text");
System.out.println("proText----"+proText);
List cityList=province.elements("city");
for (int j = 0; j < cityList.size(); j++) {
Element city=(Element) cityList.get(j);
String cityText=city.getText();
System.out.println("cityText---"+cityText);
}
}
//把document以xml形式打印出来
System.out.println(document.asXML());
}
public void insert(){
Element rootEle=document.getRootElement();
Element population=rootEle.addElement("population");
population.setText("130000");
try {
XMLWriter writer=new XMLWriter(new FileWriter(classPath+filePath));
writer.write(document);
//writer.
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Dom4JParse().parse();
//new Dom4JParse().insert();
//System.out.println("我日");
}
}