以下:
/** * <XML字符串转换成XML Document > * <功能详细描述> * @param sXml * @return * @see [类、类#方法、类#成员] */ public Document changeStringToXML(String sXml) { StringReader sr = new StringReader(sXml); InputSource is = new InputSource(sr); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(is); return doc; }
将XML生成在指定路径:
/** * 生成文件 * @param path * @param doc * @return -1:生成xml出错 0:创建成功 1:所要上报的文件已生成 */ public int writeXML(String path,Document doc) { File markFile = new File(path); if (markFile.exists()) { return 1; } FileOutputStream fos; try { fos = new FileOutputStream(path); } catch (FileNotFoundException e) { logger.debug("数据上报XML文件输出出错:系统找不到指定路径"); return -1; } OutputStreamWriter outwriter; try { outwriter = new OutputStreamWriter(fos,"UTF-8"); Source sorce = new DOMSource(doc); Result result = new StreamResult(outwriter); Transformer trans; try { trans = TransformerFactory.newInstance().newTransformer(); trans.setOutputProperty(OutputKeys.ENCODING,"UTF-8"); trans.transform(sorce,result); try { fos.close(); } catch (IOException e) { e.printStackTrace(); } return 0; } catch (TransformerConfigurationException e) { e.printStackTrace(); return -1; } catch (TransformerFactoryConfigurationError e) { e.printStackTrace(); return -1; } catch (TransformerException e) { e.printStackTrace(); return -1; } } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); return -1; } }