所需jar包
package com.test;
/*** @author 作者 E-mail: hanzl
* @version 创建时间:2018年4月22日 下午10:56:32
* 类 说明:
*/
import com.google.common.collect.Lists;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* Created by lxk on 2016/11/10
*/
public class XmlTest {
public static void main(String[] args) throws DocumentException {
xmlTest();
}
/**
* 测试解析xml文件
* @throws DocumentException
*/
@SuppressWarnings("unchecked")
private static void xmlTest() throws DocumentException {
SAXReader reader = new SAXReader();
reader.setEncoding("utf-8");
Document document;
document = reader.read(new File("src/acl.xml"));
Element root = document.getRootElement();//得到xml跟标签,此处是<root></root>
//root.elements(arg0)
List<Element> list = root.elements();
FileWriter file = null;
BufferedWriter bw = null;
try {
File newFile=new File("e:\\acl_descrip_XML.txt");
//文件不存在,创建文件
if(!newFile.exists()) newFile.createNewFile();
file = new FileWriter(newFile.getAbsolutePath(),true);
bw = new BufferedWriter(file);
for(Element e:list){
//System.out.println(e.elementText("addr-iplist"));
if(e.elementText("descrip")==null){
bw.write("");
}else{
bw.write(e.elementText("descrip"));
}
bw.newLine();
//System.out.println();
}
//跨平台的换行符
/* bw.newLine();
bw.write("地势坤,君子以厚德载物。");
bw.newLine(); */
//缓冲区的写必须有刷新
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
bw.close();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}