import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
**/
public class XmlByDom4j {
/**
* 填充Xml模板导出
* @author ChenShilin
* @date 2017-04-19
* @param xmlFilePath XML模板path
* @param xmlFileName 导出的xml文件名称
* @param mapData 填充的数据
*/
public static void FillXmlByMapData(String xmlFilePath,String xmlFileName,Map<String,String> mapData ,HttpServletResponse response){
try {
SAXReader reader = new SAXReader();
Document doc = reader.read(new File(xmlFilePath));
//得到xml文档根节点元素
Element root = doc.getRootElement();
//从根节点开始遍历所有节点
GetNodes(root,mapData);
// 创建输出格式(OutputFormat对象)
OutputFormat format = OutputFormat.createPrettyPrint();
///设置输出文件的编码,设置成当前服务器的编码
format.setEncoding(System.getProperty("file.encoding"));
XMLWriter writer = new XMLWriter(new FileWriter(new File(xmlFilePath)), format);
writer.write(doc);
writer.close();
OutPutTableByOutputStream(response, xmlFileName, xmlFilePath);
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* 从指定节点开始,递归遍历所有子节点 ,
* 并且根据节点名称填充相应的数据
* @date 2017-04-19
* @author chenShiilin
* @param node 遍历的节点
* @param mapData 需要填充的数据map
*/
private static void GetNodes(Element node , Map<String,String> mapData){
//当前节点的名称、文本内容和属性
if(mapData.containsKey(node.getName())){
String value = mapData.get(node.getName());
if(value != null && value !=""){
node.setText(mapData.get(node.getName()));
}else{
node.setText("");
}
}
//递归遍历当前节点所有的子节点
List<Element> listElement=node.elements();//所有一级子节点的list
for(Element e:listElement){//遍历所有一级子节点
GetNodes(e,mapData);//递归
}
}
/**
* 文件下载
* Action outputTableByOutputStream
* @author ChenShilin
* @date 2017-04-19
* @param response
* @param fileName 文件名称
* @param xmlFilePath XML模板path
* @throws Exception
*/
private static void OutPutTableByOutputStream(HttpServletResponse response,String fileName,String xmlFilePath) throws Exception
{
String contentType = "application/xml";//定义导出文件的格式的字符串
response.setCharacterEncoding("UTF-8");
String recommendedName = new String(fileName.getBytes("GB2312"), "ISO8859-1");//设置文件名称的编码格式
response.setContentType(contentType);//设置导出文件格式
response.setHeader("Content-Disposition", "attachment; filename="+recommendedName);
FileInputStream inputStream = new FileInputStream(new File(xmlFilePath));
//3.通过response获取ServletOutputStream对象(out)
ServletOutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer))>0){
out.write(buffer,0,len);
}
inputStream.close();
out.close();
out.flush();
}
}
转载 https://gitee.com/chensl_846/codes/6kv4f7zx8mgr30ulhic5y36