欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

字符串xml生成xml文件

程序员文章站 2022-04-12 21:29:47
/** * 将字符串的xml转换成org.w3c.dom.Document对象 * @param xml * @return...



/**
* 将字符串的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("{https://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();
}
}