/**
* 生成xml文件
*
* @param xmlStr
* @param fileName
* @param type
* @param path
* @return
* @author allen_lu
* @since 2019年12月12日10:43:15
*/
public void createXml(String xmlStr, String fileName, String type, String path) {
Document doc = strToDocument(xmlStr);
String realPath = path + File.separator + fileName + type;
try {
// 判断文件是否存在,如存在就删掉它
File file = new File(realPath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
/** 将document中的内容写入文件中 */
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new FileOutputStream(realPath));
transformer.transform(source, result);
} catch (final Exception e) {
e.printStackTrace();
}
}
/**
* 生成文件获取Document
*
* @param xmlStr
* @return
* @author allen_lu
* @since 2019年12月12日10:43:15
*/
public static Document strToDocument(String xmlStr) {
Document doc = null;
StringReader sr = new StringReader(xmlStr);
InputSource is = new InputSource(sr);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
doc = builder.parse(is);
} catch (Exception e) {
e.printStackTrace();
}
return doc;
}
生成xml文件
最新推荐文章于 2024-07-18 14:45:44 发布