SSM框架实现xml导出并在客户端下载的三种方式(本文原创,转载请标明转载地址,谢谢~)
1.使用Document创建节点
// 创建xml
Document document = DocumentHelper.createDocument();
//创建节点
Element elements = document.addElement("ImportMessage").addNamespace("xsi","http://www.w3.org/2001/XMLSchema-instance").addAttribute("xsi:noNamespaceSchemaLocation","SWImportMessagexsd.xsd");
注:第一个是创建根节点,addNamespace()定义命名空间,后面一个就是自定义属性,如下图所示:
//创建子节点
-----创建第一个子节点
Element ele = elements.addElement("Head");
Element nameEle = ele.addElement("CopMsgId").addText("普通报关单.xml");
nameEle = ele.addElement("MsgType").addText("SWDEC001");
nameEle = ele.addElement("FunctionCode").addText("0");
nameEle = ele.addElement("Format").addText("xml");
nameEle = ele.addElement("Compress").addText("0");
nameEle = ele.addElement("Version").addText("1.0");
如图所示:
-----------创建第二个子节点
Element ele2 = elements.addElement("Data");
--------创建第二个子节点的子节点
Element nameEle2 = ele2.addElement("DecMessage");
-------创建子节点的子节点
Element nameEle3 = nameEle2.addElement("DecLists");
nameEle3 = nameEle2.addElement("DecContainers");
nameEle3 = nameEle2.addElement("DecLicenseDocus");
//获取所有的节点名称
Element root = document.getRootElement();
------------创建子节点下的节点循环,例如DecLists
for (CustomsDeclareBillDetail detail:detailList) {
//找到要创造节点循环的子节点名称:root.selectSingleNode()
Element ee2 = (Element) root.selectSingleNode("//DecLists");
//创建节点循环的节点名称
Element ele6 = ee2.addElement("DecList");
Element ele7=ele7=ele6.addElement("商品编号").addText(XMLUtil.replaceNullString(detail.getCodeT())); ele7=ele6.addElement("备案序号").addText(XMLUtil.replaceNullString(detail.getRelmanNo())); ele7=ele6.addElement("商品名称").addText(XMLUtil.replaceNullString(detail.getGName())); ele7=ele6.addElement("规格型号").addText(XMLUtil.replaceNullString(detail.getgModel())); ele7= ele6.addElement("成交数量").addText(XMLUtil.replaceNullString(detail.getgQty()==null?"":detail.getgQty().toString())); ele7= ele6.addElement("成交单位").addText(XMLUtil.replaceNullString(detail.getGUnit())); ele7= ele6.addElement("法定单位").addText(XMLUtil.replaceNullString(detail.getLegalUnits())); ele7= ele6.addElement("成交总价").addText(XMLUtil.replaceNullString(detail.getDeclTotal()==null?"":detail.getDeclTotal().toString())); ele7= ele6.addElement("币制").addText(XMLUtil.replaceNullString(detail.getDeclCurr())); ele7= ele6.addElement("原产国").addText(XMLUtil.replaceNullString(detail.getOriginCountry())); ele7= ele6.addElement("征减免税方式").addText(XMLUtil.replaceNullString(detail.getDutyMode())); ele7= ele6.addElement("最终目的国").addText(XMLUtil.replaceNullString(detail.getDestCountry())); ele7= ele6.addElement("提运单号").addText(XMLUtil.replaceNullString(detail.getBillNo())); } String xmlString = document.asXML(); String xmlDoc = XMLUtil.formatXml(xmlString); String fileName = "报关单.xml"; XMLUtil.getXMLWriter(response, fileName,xmlDoc);
如下图所示:
2.使用StringBuffer拼接xml文件:
System.getProperty("line.separator");//为换行标记
StringBuffer buffer = new StringBuffer();
buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+System.getProperty("line.separator")); buffer.append("<ImportMessage xsi:noNamespaceSchemaLocation=\"SWImportMessagexsd.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"+System.getProperty("line.separator")); buffer.append("<Head>"+System.getProperty("line.separator")); buffer.append("<CopMsgId>普通报关单.xml</CopMsgId>"+System.getProperty("line.separator")); buffer.append("<MsgType>SWDEC001</MsgType>"+System.getProperty("line.separator")); buffer.append("<FunctionCode>0</FunctionCode>"+System.getProperty("line.separator")); buffer.append("<Format>xml</Format>"+System.getProperty("line.separator")); buffer.append("<Compress>0</Compress>"+System.getProperty("line.separator")); buffer.append("<Version>1.0</Version>"+System.getProperty("line.separator")); buffer.append("</Head>"+System.getProperty("line.separator")); buffer.append("<Data>"+System.getProperty("line.separator")); buffer.append("<DecMessage>"+System.getProperty("line.separator")); buffer.append("<DecLists>"+System.getProperty("line.separator"));
for (CustomsDeclareBillDetail detail:detailList) { buffer.append("<DecList>"+System.getProperty("line.separator")); buffer.append("<商品编号>"+detail.getCodeT()+"</商品编号>"+System.getProperty("line.separator")); buffer.append("<备案序号>"+detail.getRelmanNo()+"</备案序号>"+System.getProperty("line.separator")); buffer.append("<商品名称>"+detail.getGName()+"</商品名称>"+System.getProperty("line.separator")); buffer.append("<规格型号>"+detail.getgModel()+"</规格型号>"+System.getProperty("line.separator")); buffer.append("<成交数量>"+XMLUtil.replaceNullString(detail.getgQty()==null?"":detail.getgQty().toString())+"</成交数量>"+System.getProperty("line.separator")); buffer.append("<成交单位>"+detail.getGUnit()+"</成交单位>"+System.getProperty("line.separator")); buffer.append("<法定单位>"+detail.getLegalUnits()+"</法定单位>"+System.getProperty("line.separator")); buffer.append("<成交总价>"+XMLUtil.replaceNullString(detail.getDeclTotal()==null?"":detail.getDeclTotal().toString())+"</成交总价>"+System.getProperty("line.separator")); buffer.append("<币制>"+detail.getDeclCurr()+"</币制>"+System.getProperty("line.separator")); buffer.append("<原产国>"+detail.getOriginCountry()+"</原产国>"+System.getProperty("line.separator")); buffer.append("<征减免税方式>"+detail.getDutyMode()+"</征减免税方式>"+System.getProperty("line.separator")); buffer.append("<最终目的国>"+detail.getDestCountry()+"</最终目的国>"+System.getProperty("line.separator")); buffer.append("<提运单号>"+detail.getBillNo()+"</提运单号>"+System.getProperty("line.separator")); buffer.append("</DecList>"+System.getProperty("line.separator")); } buffer.append("</DecLists>"+System.getProperty("line.separator")); buffer.append("</DecMessage>"+System.getProperty("line.separator")); buffer.append("</Data>"+System.getProperty("line.separator")); buffer.append("</ImportMessage>"); String xmlString = buffer.toString(); String xmlDoc = XMLUtil.formatXml(xmlString); String fileName = "报关单.xml"; XMLUtil.getXMLWriter(response, fileName,xmlDoc);
3.使用String += 输出xml文件:
string strXML = "<?xml version=\"1.0\"?>"; strXML+="<books><bookdata id=\"1\">"; strXML+="<title>C# premier</title>"; strXML += "<year>2005</year>"; strXML+="<publisher> Qinghua University Press</publisher>"; strXML+="<Author>hou </Author>"; strXML+="<pagers>500 </pagers>"; strXML+="<description> c# fundation knowledge</description>"; strXML+="<Price>50.00</Price>"; strXML+="</bookdata>"; strXML+="<bookdata id=\"2\">"; strXML+="<title>xml premier</title>"; strXML+="<year>2005</year>"; strXML+="<publisher> Peking University Press</publisher>"; strXML+="<Author>Leo </Author>"; strXML+="<pagers>400 </pagers>"; strXML+="<description> xml fundation knowledge</description>"; strXML+="<Price>45.00</Price>"; strXML+="</bookdata>"; strXML+="<bookdata id=\"3\">"; strXML+="<title>UML</title>"; strXML+="<year>2005</year>"; strXML+="<publisher> Peking University Press</publisher>"; strXML+=" <Author>James </Author>"; strXML+=" <pagers>650 </pagers>"; strXML+=" <description>UML fundation knowledge</description>"; strXML += " <Price>85.00</Price>"; strXML+=" </bookdata></books>";
Response.ContentType = "text/xml";
Response.Charset = "UTF-8";
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(strXML);
doc.Save(Response.OutputStream);
Response.End();
或:
String xmlDoc = XMLUtil.formatXml(strXML);
String fileName = "报关单.xml";
XMLUtil.getXMLWriter(response, fileName,xmlDoc);
最后附上调用的工具包:
public class XMLUtil { private final static org.slf4j.Logger logger = LoggerFactory.getLogger(XMLUtil.class); private XMLUtil() { } /** * 根据字符串创建 document 对象 * * @param xmlStr * @return */ public static Document getDocumentByString(String xmlStr) { Document doc = null; try { doc = DocumentHelper.parseText(xmlStr); } catch (DocumentException e) { logger.error("字符串转换成XML失败:" + e.getMessage()); } return doc; } /** * 设置response的返回信息 * @param response * @param fileName * @return XMLWriter */ public static XMLWriter getXMLWriter(HttpServletResponse response,String fileName,String xmlDoc) { XMLWriter writer = null; OutputStream os = null; try { //定义xml文件的格式 OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); //准备输出xml文件 writer =new XMLWriter(response.getOutputStream(),format); response.setContentType("text/xml;charset=UTF-8"); response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1")); os = response.getOutputStream(); os.write(xmlDoc.getBytes("UTF-8")); writer.setOutputStream(os); }catch (Exception e){ logger.error("导出xml时获取XMLWriter出错:"+e); }finally { if(null != os){ try { os.close(); } catch (IOException e) { logger.error("关闭outputStream出错:"+e); } } } return writer; } public static String formatXml(String xml) throws DocumentException, IOException{ SAXReader saxReader = new SAXReader(); Document document = saxReader.read(new ByteArrayInputStream(xml.getBytes())); //创建输出格式 OutputFormat format = OutputFormat.createPrettyPrint(); //制定输出xml的编码类型 format.setEncoding("UTF-8"); StringWriter writer = new StringWriter(); //创建一个文件输出流 XMLWriter xmlwriter = new XMLWriter(writer, format); //将格式化后的xml串写入到文件 xmlwriter.write(document); String returnValue = writer.toString(); writer.close(); //返回编译后的字符串格式 return returnValue; } /** * 根据file获得Document * @param file MultipartFile * @return Document */ public static Document getDocumentByFile(MultipartFile file){ File file1 = new File(file.getOriginalFilename()); Document document = null; try { file.transferTo(file1); //创建SAXReader对象 SAXReader reader = new SAXReader(); //读取文件 转换成Document document = reader.read(file1); } catch (IOException e) { document = null; logger.error("文件转换出错:"+e); } catch (DocumentException e) { document = null; logger.error("读取文件出错:"+e); } return document; } public static void main(String[] args){ //创建xml Document document = DocumentHelper.createDocument(); //创建节点 Element elements = document.addElement("list"); for (int i = 0; i < 1; i++) { Element ele = elements.addElement("CustomsDeclareBill"); ele.addAttribute("id", "6"); Element nameEle = ele.addElement("提运单号"); nameEle.setText("55555"); OutputFormat format = OutputFormat.createPrettyPrint();//Format格式!! format.setEncoding("UTF-8"); XMLWriter writer = null; try { writer = new XMLWriter(format); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { //讲xml文档输出到控制台上 writer.write(document); } catch (IOException e) { e.printStackTrace(); } } } public static String replaceNullString(String str){ if(str == null ){ return ""; }else if(str.equals("")){ return ""; }else{ return str; } } }
最后导出个xml文件如图所示:
以上三种方法都是本人亲测并实现的功能,有什么问题欢迎留言询问~如果觉得此文对你有帮助的话,顶一下文哦~
部分代码参考自http://www.cnblogs.com/zgqys1980/archive/2009/10/17/1585052.html