import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.jboss.logging.Logger;
import org.w3c.dom.Document;
import com.alibaba.fastjson.JSONObject;
public class XmlUtils {
private final Logger logger = Logger.getLogger(getClass());
/**
* 生成xml方法
*
* @param xmlName
*/
public static JSONObject createXmlFile(Document document, String xmlName) {
PropUtils propUtils = new PropUtils("cfg.properties");
JSONObject json = new JSONObject();
try {
// 创建解析器工厂
/*DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
Document document = db.newDocument();*/
// 不显示standalone="no"
document.setXmlStandalone(true);
TransformerFactory tff = TransformerFactory.newInstance();
Transformer tf = tff.newTransformer();
// 输出内容是否使用换行
tf.setOutputProperty(OutputKeys.INDENT, "yes");
String path = propUtils.getProp("xmlPathHeader");
String fullPath = path + File.separator + xmlName;
// 创建xml文件并写入内容
tf.transform(new DOMSource(document), new StreamResult(new File(fullPath)));
json.put("xmlUrl", path);
System.out.println("生成并保存" + xmlName + ",成功");
} catch (Exception e) {
e.printStackTrace();
System.out.println("生成xml失败");
}
return json;
}
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();
System.out.println("FileNotFound错误" + e.getMessage());
} catch (IOException e) {
System.out.println("转换IO错误" + e.getMessage());
e.printStackTrace();
}
xmlString = new String(strBuffer); //构建String时,可用byte[]类型,
System.out.println("xml文件转换后的字符串:" + xmlString);
return xmlString;
}
public static void main(String[] args) {
Long start = System.currentTimeMillis();
// createXmlFile();
System.out.println("运行时间:" + (System.currentTimeMillis() - start));
}
}
Java生成xml文件的四种方式
https://www.cnblogs.com/lin346112883/p/10212985.html
xml字符串保存xml文件或xml转换String字符串
https://blog.csdn.net/Xiaodongge521/article/details/84772669