不解析,直接贴代码
public class TransformService { private Logger log = Logger.getLogger(TransformService.class); private final String TEMPLET = "templet"; /** * 转换类 * * @param xmlReq * @param xslTempletName * @return */ public String xmlTransform(String xmlReq, String xslTempletName) { // TODO Auto-generated method stub try { log.info("Para xml:" + xmlReq); log.info("Para xslTempletName:" + xslTempletName); Resource res = new ClassPathResource(TEMPLET + "/" + xslTempletName + ".xsl"); log.info("Templet URL:" + res.getFile() == null ? null : res .getFile().toString()); Source templet = new StreamSource(res.getFile()); Transformer transf = TransformerFactory.newInstance() .newTransformer(templet); Document req = DocumentHelper.parseText(xmlReq); Source xmlSource = new StreamSource(new StringReader(req.asXML())); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Result result = new StreamResult(baos); transf.setOutputProperty(OutputKeys.METHOD, "xml"); transf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transf.setOutputProperty(OutputKeys.INDENT, "yes"); transf.transform(xmlSource, result); ByteArrayInputStream bais = new ByteArrayInputStream( baos.toByteArray()); String path = res.getFile().toString(); String rPath = path.substring(0, path.lastIndexOf("classes")); File folder = new File(rPath + "xmlFolder"); log.info("XML_FOLD_DIR:" + folder == null ? null : folder .toString()); if (!folder.exists()) { folder.mkdir(); } File file = new File(folder + File.separator + xslTempletName + "_" + new Date().getTime() + ".xml"); log.info("XML_FILE_URL:" + file == null ? null : file.toString()); FileOutputStream fis = new FileOutputStream(file); fis.write(baos.toByteArray()); fis.close(); SAXReader sax = new SAXReader(); Document resXML = sax.read(bais); log.info(resXML.asXML()); System.out.println(resXML.asXML()); return resXML.asXML(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); log.error(e.getMessage()); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); log.error(e.getMessage()); } catch (TransformerFactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); log.error(e.getMessage()); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); log.error(e.getMessage()); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); log.error(e.getMessage()); } return null; } public static void main(String[] args) { try { TransformService ts = new TransformService(); Resource res = new ClassPathResource("templet/DY.xml"); SAXReader sax = new SAXReader(); Document resXML = sax.read(res.getFile()); ts.xmlTransform(resXML.asXML(), "DY2HS"); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }