使用dom4j生成xml,首先导入jar包
dom4j-1.6.1.jar
在spring通过依赖注入导入包
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
生成xml文件,首先创建根节点:
Document document = DocumentHelper.createDocument();
Element root = document.addElement("MatchCode");--------->addElement添加子节点
Element e = root.addElement("brandNames");
e.addAttribute("typeId","1");------------->addAttribute属性添加属性
e.addText("hfud");------------>addText属性添加文字
-------------------------------------------------------------------------------------
<MatchCode>
<BrandNames typeid ="1">hfud</BrandNames>
</MatchCode>
导出到xml
XMLWriter out = null;
BufferedWriter bw = null;
OutputStreamWriter osw = null;
try {
osw = new OutputStreamWriter(outputStream,"UTF-8");//指定编码,防止写中文乱码
bw = new BufferedWriter(osw);
//对xml输出格式化
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
out = new XMLWriter(bw, format);
out.write(document);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(out != null) {
out.close();
}
if(bw != null) {
bw.close();
}
if(osw != null) {
osw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
文件直接导出
resp.setHeader("content-disposition","attachment;filename=data.xml");