上传xml文件数据到数据库思路:首先上传需要建校验xml字段的校验文件,然后程序根据后台写好的xml数据文件路径自动读取数据文件,再上传数据文件到数据库之前先根据校验文件校验上传的数据文件的字段是否合法,进行判断。
前台页面 /WEB-INF/jsp/test/uploadExcel.jsp
<form id="uploadAuditedFileForm" action="../upload/uploadAuditedXML" method="post" enctype="multipart/form-data"> <input id="uploadAuditedFile" type="file" name="file" onchange="javascript:CheckAuditedFileType()" /> <input id="uploadAuditedBtn" type="submit" disabled="disabled" value="上传引擎审核结果文件" /> </form>
后台代码
@Controller
@RequestMapping(value = "/upload")
public class UploadSaleDataAction类
@RequestMapping(value = "/uploadAuditedXML") public String uploadAuditedXML(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) { String path = UPLOAD_DIR + File.separator; String fileName = file.getOriginalFilename(); fileName = "Audited.xml"; File targetFile = new File(path, fileName); if (!targetFile.exists()) { targetFile.mkdirs(); } // 保存 try { file.transferTo(targetFile); System.out.println(targetFile.getPath()); } catch (Exception e) { e.printStackTrace(); } engineResult.storeEngineResultToSamsDb(); return GO_UPLAODEXCEL; } }
校验xml文件 StoreEngineResult类
/** * 将引擎输出结果存储到销售审核数据库中 */ public void storeEngineResultToSamsDb() { // 通过xsd文件验证xml文件合法性 if (!parse.validateXMLByXSD("/usr/app/saleData/Audited.xml", "/usr/app/saleData/engineoutput.xsd")) { log.error("验证失败!"); return; } parse.parseAuditedXML("/usr/app/saleData/Audited.xml"); }
解析xml类
@Component
public class ParseXML
/** * 通过XSD(XML Schema)校验XML * * @return */ public boolean validateXMLByXSD(String xmlPath, String xsdPath) { // xmlPath = "D:\xmltest\source\TRANSACTION\test.xml"; // xsdPath = "D:\xmltest\validator\test.xsd"; boolean flag = false; try { // 创建默认的XML错误处理器 XMLErrorHandler errorHandler = new XMLErrorHandler(); // 获取基于 SAX 的解析器的实例 SAXParserFactory factory = SAXParserFactory.newInstance(); // 解析器在解析时验证 XML 内容。 factory.setValidating(true); // 指定由此代码生成的解析器将提供对 XML 名称空间的支持。 factory.setNamespaceAware(true); // 使用当前配置的工厂参数创建 SAXParser 的一个新实例。 SAXParser parser = factory.newSAXParser(); // 创建一个读取工具 SAXReader xmlReader = new SAXReader(); // 获取要校验xml文档实例 Document xmlDocument = (Document) xmlReader.read(new File(xmlPath)); // 设置 XMLReader 的基础实现中的特定属性。核心功能和属性列表可以在 // [url]http://sax.sourceforge.net/?selected=get-set[/url] 中找到。 parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "file:" + xsdPath); // 创建一个SAXValidator校验工具,并设置校验工具的属性 SAXValidator validator = new SAXValidator(parser.getXMLReader()); // 设置校验工具的错误处理器,当发生错误时,可以从处理器对象中得到错误信息。 validator.setErrorHandler(errorHandler); // 校验 validator.validate(xmlDocument); XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint()); // 如果错误信息不为空,说明校验失败,打印错误信息 if (errorHandler.getErrors().hasContent()) { System.out.println("XML文件通过XSD文件校验失败!"); writer.write(errorHandler.getErrors()); log.error("XML文件通过XSD文件校验失败!"); log.error(errorHandler.getErrors().asXML()); return flag; } flag = true; } catch (Exception ex) { log.error("XML文件: " + xmlPath + " 通过XSD文件:" + xsdPath + "检验失败。 原因: " + ex.getMessage()); System.out.println("XML文件: " + xmlPath + " 通过XSD文件:" + xsdPath + "检验失败。 原因: " + ex.getMessage()); } return flag; }
校验成功后开始解析xml数据文件
/** * 解析XML * * @param xmlPath * @return * @throws Exception */ public void parseAuditedXML(String xmlPath) { try { Element root = read(xmlPath).getRootElement(); for (Iterator<?> transactions = root.elementIterator("TRANSACTION"); transactions .hasNext();) { Element transactionElement = (Element) transactions.next(); for (Iterator<?> ticketsElement = transactionElement .elementIterator("AUDITEDTICKET"); ticketsElement.hasNext();) { Element ticketElement = (Element) ticketsElement.next(); AuditedTicketEngineOut auditedTicket = new AuditedTicketEngineOut(); auditedTicket = setTicketInfo(ticketElement, auditedTicket); ticketService.saveEngineAuditOut(auditedTicket); } } } catch (DocumentException e) { e.printStackTrace(); log.error("解析文件失败!"); } }
将解析的元素添加到对象中
/** * Ticket对象设值 * * @param ticketElement * @param ticket * @throws ParseException */ @SuppressWarnings("finally") private AuditedTicketEngineOut setTicketInfo(Element ticketElement, AuditedTicketEngineOut auditedTicket) { try { auditedTicket.setTktNo(getText(ticketElement.element("TKT_NO")) == null ? null : getText(ticketElement.element("TKT_NO"))); // auditedTicket // .setEngineRefAuditDate(getText(ticketElement.element("ENGINE_REF_AUDIT_DATE")) == null ? null // : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") // .parse(getText(ticketElement.element("ENGINE_REF_AUDIT_DATE")) // .contains("T") == false ? getText(ticketElement // .element("ENGINE_REF_AUDIT_DATE")) : getText( // ticketElement.element("ENGINE_REF_AUDIT_DATE")) // .replace("T", " "))); auditedTicket.setEngineRefAuditDate(getText(ticketElement .element("ENGINE_REF_AUDIT_DATE")) == null ? null : new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss").parse(getText(ticketElement .element("ENGINE_REF_AUDIT_DATE")) == null ? null : getText(ticketElement .element("ENGINE_REF_AUDIT_DATE")))); auditedTicket .setFareRefAmt(getText(ticketElement.element("FARE_REF_AMT")) == null ? null : new BigDecimal(getText(ticketElement.element("FARE_REF_AMT")))); auditedTicket .setCommCalBase(getText(ticketElement.element("COMM_CAL_BASE")) == null ? null : getText(ticketElement.element("COMM_CAL_BASE"))); auditedTicket .setCommRateRefAmt(getText(ticketElement.element("COMM_RATE_REF_AMT")) == null ? null : new BigDecimal(getText(ticketElement.element("COMM_RATE_REF_AMT")))); auditedTicket .setCommRefAmt(getText(ticketElement.element("COMM_REF_AMT")) == null ? null : new BigDecimal(getText(ticketElement.element("COMM_REF_AMT")))); auditedTicket.setTaxRefAmt(getText(ticketElement.element("TAX_REF_AMT")) == null ? null : new BigDecimal(getText(ticketElement.element("TAX_REF_AMT")))); auditedTicket .setRefundFeeRefAmt(getText(ticketElement.element("REFUNDFEE_REF_AMT")) == null ? null : new BigDecimal(getText(ticketElement.element("REFUNDFEE_REF_AMT")))); // auditedTicket // .setExchangeFeeRefAmt(getText(ticketElement.element("EXCHANGEFEE_REF_AMT")) == null ? null // : new BigDecimal(getText(ticketElement.element("EXCHANGEFEE_REF_AMT")))); auditedTicket .setFareErrorCode(getText(ticketElement.element("FARE_ERROR_CODE")) == null ? null : getText(ticketElement.element("FARE_ERROR_CODE"))); auditedTicket .setCommErrorCode(getText(ticketElement.element("COMM_ERROR_CODE")) == null ? null : getText(ticketElement.element("COMM_ERROR_CODE"))); auditedTicket .setTaxErrorCode(getText(ticketElement.element("TAX_ERROR_CODE")) == null ? null : getText(ticketElement.element("TAX_ERROR_CODE"))); auditedTicket .setFareAuditMode(getText(ticketElement.element("FARE_AUDIT_MODE")) == null ? null : getText(ticketElement.element("FARE_AUDIT_MODE"))); auditedTicket .setCommAuditMode(getText(ticketElement.element("COMM_AUDIT_MODE")) == null ? null : getText(ticketElement.element("COMM_AUDIT_MODE"))); auditedTicket .setTaxAuditMode(getText(ticketElement.element("TAX_AUDIT_MODE")) == null ? null : getText(ticketElement.element("TAX_AUDIT_MODE"))); auditedTicket .setEngRuleOldResult(getText(ticketElement.element("ENG_RULE_OLDRESULT")) == null ? null : getText(ticketElement.element("ENG_RULE_OLDRESULT"))); auditedTicket = parseTicketChildNode(ticketElement, auditedTicket); } catch (ParseException e) { e.printStackTrace(); } finally { return auditedTicket; } }
添加ticket下的子标签元素
/** * 解析TICKET标签下的子标签对象 * * @param ticketElement * @param ticket * @throws ParseException */ private AuditedTicketEngineOut parseTicketChildNode(Element ticketElement, AuditedTicketEngineOut auditedTicket) { List<AuditedSector> sectors = setSectorInfo(ticketElement); List<AuditedFareComponent> fareComponents = setFareComponetInfo(ticketElement); List<AuditedTicketTax> ticketTaxs = setTicketTaxInfo(ticketElement); List<AuditedCouponTax> couponTaxs = setCouponTaxInfo(ticketElement); auditedTicket.setAuditedSectors(sectors); auditedTicket.setAuditedCouponTaxs(couponTaxs); auditedTicket.setAuditedFareComponents(fareComponents); auditedTicket.setAuditedTicketTaxs(ticketTaxs); return auditedTicket; }
添加子元素,其他子元素以此类推
/** * Sector对象设值 * * @param ticketElement * @return * @throws ParseException */ private List<AuditedSector> setSectorInfo(Element ticketElement) { List<AuditedSector> sectors = new ArrayList<AuditedSector>(); for (Iterator<?> sectorsElement = ticketElement.elementIterator("AUDITEDSECTOR"); sectorsElement .hasNext();) { Element sectorElement = (Element) sectorsElement.next(); AuditedSector sector = new AuditedSector(); sector.setTktNo(getText(sectorElement.element("TKT_NO")) == null ? null : getText(sectorElement.element("TKT_NO"))); sector.setCpnNo(getText(sectorElement.element("CPN_NO")) == null ? null : Long .parseLong(getText(sectorElement.element("CPN_NO")))); sector.setRfdFeeRefAmt(getText(sectorElement.element("CHANGEFEE_REF_AMT")) == null ? null : new BigDecimal(getText(sectorElement.element("CHANGEFEE_REF_AMT")))); sectors.add(sector); } return sectors; }
然后保存引擎输入结果
/* * 保存引擎输出结果 */ @Override @Transactional public void saveEngineAuditOut(AuditedTicketEngineOut auditedTicketEngineOut) { Ticket ticket = this.findTicketByTktNo(auditedTicketEngineOut.getTktNo()); if (ticket != null) { convertTicket(auditedTicketEngineOut, ticket); if ("N".equals(ticket.getTicketBasicSale().getSaleType())) { NormalTicket normal = (NormalTicket) ticket; normal.setFciFareComponents(convertFareComponet(normal.getFciFareComponents(), auditedTicketEngineOut)); normal.setTaxs(convertTicketTax(normal.getTaxs(), auditedTicketEngineOut)); normal.setCouponTaxs(convertCouponTax(normal.getCouponTaxs(), auditedTicketEngineOut)); normal.setFciSectors(convertFciSector(normal.getFciSectors(), auditedTicketEngineOut)); ticketDao.updateNormalTicket(normal); } else if ("E".equals(ticket.getTicketBasicSale().getSaleType())) { ExchangeTicket exchange = (ExchangeTicket) ticket; exchange.setFciFareComponents(convertFareComponet(exchange.getFciFareComponents(), auditedTicketEngineOut)); exchange.setTaxs(convertTicketTax(exchange.getTaxs(), auditedTicketEngineOut)); exchange.setCouponTaxs(convertCouponTax(exchange.getCouponTaxs(), auditedTicketEngineOut)); exchange.setFciSectors(convertFciSector(exchange.getFciSectors(), auditedTicketEngineOut)); AuditInfo changeFeeInfo = exchange.getChangeFeeInfo(); changeFeeInfo.setRefAmt(auditedTicketEngineOut.getExchangeFeeRefAmt()); // EXCHANGEFEE_REF_AMT exchange.setChangeFeeInfo(changeFeeInfo); ticketDao.updateExchangeTicket(exchange); } else if ("R".equals(ticket.getTicketBasicSale().getSaleType())) { RefundTicket refund = (RefundTicket) ticket; refund.setTaxs(convertTicketTax(refund.getTaxs(), auditedTicketEngineOut)); refund.setCouponTaxs(convertCouponTax(refund.getCouponTaxs(), auditedTicketEngineOut)); refund.setFciSectors(convertFciSector(refund.getFciSectors(), auditedTicketEngineOut)); AuditInfo refundFeeInfo = refund.getRefundFeeInfo(); refundFeeInfo.setRefAmt(auditedTicketEngineOut.getRefundFeeRefAmt());// REFUNDFEE_REF_AMT refund.setRefundFeeInfo(refundFeeInfo); ticketDao.updateRefundTicket(refund); } } }
创建的xml数据文件和xsd校验文件
附录
检验文件
数据文件xml