xml字符串保存xml文件或xml转换String字符串
废话不多说,直接上主题,先来一个xml字符串保存xml文件的方法。
/**
* 字符串转xml文件并保存指定路径
* @param xmlStr xml字符串
* @param fileName 文件名称
* @param type 文件类型(后缀)
* @param path (存放路径)
* @return
*/
@SuppressWarnings("deprecation")
public static String createXml(String xmlStr,String fileName,String type,String path) {
Document doc = strToDocument(xmlStr);
String realPath = path + fileName + type;
try {
// 判断文件是否存在,如存在就删掉它
File file = new File(realPath);
if (!file.getParentFile().exists()) {
//如果不存在则创建
file.getParentFile().mkdirs();
logger.info("==============文件目录不存在,新建文件==============");
}
/** 将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 exception) {
logger.info("更新" + fileName + "出错:"+exception);
}
//返回文件保存路径
return path + fileName + type;
}
/**
* 字符串转Document
* @param xmlStr
* @return
*/
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 (ParserConfigurationException e) {
logger.info("ParserConfiguration错误"+e);
} catch (SAXException e) {
logger.info("SAX错误"+e);
} catch (IOException e) {
logger.info("IO错误"+e);
}
return doc;
}
不明白请仔细看注释,可以直接复制粘贴使用;
接下来是根据路径将xml文件转换为xml字符串
/**
* xml文件转换字符串
* @param path
* @return
*/
public static String XmlFileToStr(String path){
String xmlString = "";
byte[] strBuffer = null;
InputStream in = null;
int flen = 0;
File xmlfile = new File(path);
try {
in = new FileInputStream(xmlfile);
flen = (int)xmlfile.length();
strBuffer = new byte[flen];
in.read(strBuffer, 0, flen);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
logger.info("FileNotFound错误"+e.getMessage());
} catch (IOException e) {
logger.info("转换IO错误"+e.getMessage());
e.printStackTrace();
}
xmlString = new String(strBuffer); //构建String时,可用byte[]类型,
logger.info("xml文件转换后的字符串:"+xmlString);
return xmlString;
}
相信大家可以看懂,其实很简单。有问题请留言告知。希望对大家有点帮助!
还没有评论,来说两句吧...