加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

字符串xml生成xml文件

发布时间:2020-12-16 06:31:56 所属栏目:百科 来源:网络整理
导读:/** * 将字符串的xml转换成org.w3c.dom.Document对象 * @param xml * @return */ public static Document getDocument(String xml) { Document document = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder
/** * 将字符串的xml转换成org.w3c.dom.Document对象 * @param xml * @return */ public static Document getDocument(String xml) { Document document = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputStream is = new ByteArrayInputStream(xml.getBytes()); document = db.parse(is); } catch (Exception e) { e.printStackTrace(); } return document; } /** * 将org.w3c.dom.Document对象写入到指定文件 * * @param doc * @param fileName * @throws Exception */ private static void outputXml(Document doc,String fileName) { try { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); DOMSource source = new DOMSource(doc); transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT,"yes");//增加换行缩进,但此时缩进默认为0 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2");//设置缩进为2 PrintWriter pw = new PrintWriter(( new OutputStreamWriter( new FileOutputStream(fileName),"UTF-8"))); StreamResult result = new StreamResult(pw); transformer.transform(source,result); } catch (Exception e) { e.printStackTrace(); } }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读